0

This is a nice evening project, but actually i'm stuck with some headache.

All I need is a function like this example:

result = set("itemCategories[0].items[0].name", "Test")

which should return:

{ itemCategories: [
   {
     items: [ {name: "Test"} ] 
   }
}]

...and in case of the given attribute "itemCategories[1].items[2].name" this result:

{ itemCategories: [
  null,
  {
    items: [
      null,
      null, 
      {name: "Test"} 
    ] 
  }
}]
3
  • You should be able to adapt the solutions here to do that. Commented Aug 16, 2017 at 15:54
  • 1
    Why do you need to pass a string? Why not aim to just do itemCategories[0].items[0].name = "Test"? Commented Aug 16, 2017 at 15:56
  • @Shard the String is given from another System Commented Aug 16, 2017 at 16:46

2 Answers 2

1

Use lodash#set:

result = lodash.set({}, "itemCategories[0].items[0].name", "Test")
Sign up to request clarification or add additional context in comments.

Comments

0

If you are asking about the vanilla JavaScript Set method then you could do this.

/* this is what you are trying to get.
{ itemCategories: [
   {
     items: [ {name: "Test"} ] 
   }
}]
*/

var mySet = new Set(); // your set object.

Create your data (number, text, string, object, array, null).

ver data1 = 365;
ver data2 = 'Dragonfly';
ver data3 = {name: 'Bobby', age: 20000, job: 'dj'};

Then you just add to that set using its add method.

mySet.add(data1);
mySet.add(data2);
mySet.add(data3);

So to get what you are looking for you would write this.

var itms = {items: [{name: 'test'}]};

mySet.add(itms);

The good thing about set is that is like an array. So you can use forEach.

mySet.forEach( function(val){
    console.log(val); // gets all your data.
});

You can even check if a value is in your data using the has method.

mySet.has(365); // true
mySet.has(36500000); as false

JavaScript Set

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.