javascriptobjectreact-nativeassign

React-Native - Object.assign children change


Sorry 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 which I have to set for multiple children. (Doing some filter stuff)

Thanks for your help


Solution

  • 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.