0

My object is already defined. I want to insert variables at particular indexes in the object.

Given message object:

message=[{
  person:{
      actions:[{test:1},{test:2}]
  },
  person:{}
},
{
  person:{
      actions:[{test:3},{test:4}]
  },
  person:{}
}]

1) If my string = "message[0].person.actions[1].visible".
This means I need to insert visible=null at index=1 of actions.
So message object becomes:

message=[{
  person:{
      actions:[{test:1},{test:2,visible:null}]
  }
},
{
  person:{
      actions:[{test:3},{test:4}]
  }
}]

2) If string="message[1].person.accessible",
So message Object become:

message=[{
  person:{
      actions:[{test:1},{test:2}]
  }
},
{
  person:{
      accessible:null,
      actions:[{test:3},{test:4}]
  }
}]

I thought of doing split('[') and get that index and insert in that object. Let me know if there are any libraries out there simplifying this for more complex data structure.

This question got closed along with a link to question [Accessing nested JavaScript objects with string key My question is different than above mentioned link. I am asking about inserting a new field at particular location in object.

Helping hand
  • 2,800
  • 2
  • 19
  • 31
  • You would use the code in the associated question to traverse your object. Which is a huge piece of what you need to do to add a new property. Your next steps would be something along the lines of removing the new field from the string, then traversing your object, then assiging the property. – hungerstar Dec 05 '19 at 23:06

1 Answers1

0

Just mutate the object by assigning it a property.

message[0].person.actions[1].visible = null;

This should work.

aPurpleDev
  • 123
  • 1
  • 12
  • `"message[0].person.actions[1].visible"` is a string in my case, not sure what you mean by mutate. This string tells that I need to insert visible at action's index=1 – Helping hand Dec 04 '19 at 17:10