I have an object like this:
myObj = {
prop1: 'prop1_value',
prop2: 'prop2_value',
subObj: {
subProp1: 'subProp1_value',
subProp2: 'subProp2_value',
subProp3: 'subProp3_value',
subprop4: 'subProp4_value',
},
};
and an array like this:
myArr = [
'arrayVal_1',
'arrayVal_2',
'arrayVal_3',
'arrayVal_4',
];
For context, subObj and myArr always have the same length.
What I am trying to do is map each of the values from myArr onto the values of subObj.
myObj would look like this when done:
myObj = {
prop1: 'prop1_value',
prop2: 'prop2_value',
subObj: {
subProp1: 'arrayVal_1',
subProp2: 'arrayVal_2',
subProp3: 'arrayVal_3',
subprop4: 'arrayVal_4',
},
};
I could manually assign the values to each key individually, but that just seems sloppy. I've tried looping with Object.keys, Object.entries, and Object.values on myObj but just can't seem to reason through this one. Thanks.
CodePudding user response:
Using Object#keys
and Array#forEach
:
const
myObj = {
prop1: 'prop1_value',
prop2: 'prop2_value',
subObj: { subProp1: 'subProp1_value', subProp2: 'subProp2_value', subProp3: 'subProp3_value', subprop4: 'subProp4_value' }
},
myArr = [ 'arrayVal_1', 'arrayVal_2', 'arrayVal_3', 'arrayVal_4' ];
const { subObj } = myObj;
Object.keys(subObj).forEach((prop, index) => { subObj[prop] = myArr[index] });
console.log(myObj);
CodePudding user response:
You could do it with Object.fromEntries
and Object.keys
this way:
myObj.subObj = Object.fromEntries(Object.keys(myObj.subObj).map((k,i) => [k, myArr[i]]))
Be aware there are currently no safe-guards of any kind, so you might want to check if the two datastructures fit, before doing this.
If you have something that you can order by object's keys by, you can also use sort
to ensure you assign the correct values to the correct keys, because the resulting order of Object.keys
is not guaranteed
myObj.subObj = Object.fromEntries(Object.keys(myObj.subObj)
.sort((a,b) => a.localeCompare(b)) //sort keys ascending by name
.map((k,i) => [k, myArr[i]]))
CodePudding user response:
You want to loop your keys and array together. One way is to try like this:
const myObj = {
prop1: 'prop1_value',
prop2: 'prop2_value',
subObj: {
subProp1: 'subProp1_value',
subProp2: 'subProp2_value',
subProp3: 'subProp3_value',
subprop4: 'subProp4_value',
},
};
const myArr = ['arrayVal_1', 'arrayVal_2', 'arrayVal_3', 'arrayVal_4'];
const keys = Object.keys(myObj.subObj); // You should actually sort these according to myArr to ensure safety
for (let i = 0; i < myArr.length; i ) {
myObj.subObj[keys[i]] = myArr[i];
}
console.log(myObj);