Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Map array values onto object key values

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading