0

sry if this question is still there but i searched for it and i didn´t find a solution. Also i couldn´t get any hint out of the Developer.Mozilla website where Objects.assign etc. is described well.

The question:

How can i change the children of an object? With exactly the output i described in the following.

Sample-Code

var obj= {test: [{a: 2}, {b: 3}]};
var newChildren = [{a: 3}, {b: 5}, {c: 1}];

//I read the obj key value by the following:
var objKey = Object.entries(obj)[0][0]

//Here i want to have some code to get the following result
//My momentary regarding to @webdeb

var output = Object.assign({}, {objKey: newChildren})

actual output: // {objKey: [{a: 3}, {b: 5}, {c: 1}]}

wanted output: // {test: [{a: 3}, {b: 5}, {c: 1}]}

I have no other option to get the code in some other format so the "input" is needed in the way i described. And i need to set the objKey as a variable, because i have multiple keys in my code wich i have to set for multiple children. (Doing some filter stuff)

Thanks for your help

BR Jonathan

Community
  • 1
  • 1
Jonathan Stellwag
  • 3,843
  • 4
  • 25
  • 50

2 Answers2

1

First of all, don't use Object as variable Name..

Ok, lets say the Object is now obj

Without modification of the obj

var newObj = Object.assign({}, obj, {test: newChildren})

Or just, (modifies the obj)

obj.test = newChildren

Is it what you are looking for?

webdeb
  • 12,993
  • 5
  • 28
  • 44
  • Hey webdeb. Thanks for your fast response. It works almost as i wanted. Just the "test" has to be variable. I UPDATED the question for further and detailed information. And ofc I edited the var Object :) – Jonathan Stellwag Jul 12 '16 at 07:42
1

Following solution gave me the exact result i wanted:

obj[objKey] = newChildren;

console.log(obj) // {test: [{a: 3}, {b: 5}, {c: 1}]}

I took this solution regarding to the question:

How can I add a key/value pair to a JavaScript object?

The importance for me was to have the object-key as a variable. The described solution gives me the option to add a value tomore than just one static key.

Community
  • 1
  • 1
Jonathan Stellwag
  • 3,843
  • 4
  • 25
  • 50