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"} 
    ] 
  }
}]
Chilian
  • 1,257
  • 1
  • 11
  • 20
  • You should be able to adapt [the solutions here](https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key) to do that. – T.J. Crowder Aug 16 '17 at 15:54
  • 1
    Why do you need to pass a string? Why not aim to just do itemCategories[0].items[0].name = "Test"? – Shardj Aug 16 '17 at 15:56
  • @Shard the String is given from another System – Chilian Aug 16 '17 at 16:46

2 Answers2

1

Use lodash#set:

result = lodash.set({}, "itemCategories[0].items[0].name", "Test")
Ryan Huang
  • 3,849
  • 2
  • 13
  • 11
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

andre mcgruder
  • 1,120
  • 1
  • 9
  • 12