Search code examples
javascriptarraysobjectfor-in-loop

How to assign an object property value as another object property?


I have the following JavaScript code:

const data = {
  columnFields: {
    columnField1: 'FieldValue1',
    columnField2: 'FieldValue2',
    columnField3: 'FieldValue3',
  },

  dataSets: [
    {
      columnProp1: 'value1',
      columnProp2: 'value2',
      columnProp3: 'value3',
    },
    {
      columnProp1: 'value11',
      columnProp2: 'value22',
      columnProp3: 'value33',
    },
  ],
};

I would like to see the following output from this data:

const expectedOutput = [
  {
    FieldValue1: 'value1',
    FieldValue2: 'value2',
    FieldValue3: 'value3',
  },
  {
    FieldValue1: 'value11',
    FieldValue2: 'value22',
    FieldValue3: 'value33',
  },
];

I have tried the following following solution

function processData() {
  const processDataSet = [];
  const obj = {};
  data.dataSets.forEach((item) => {
    for (const key in item) {
      const element = item[key];
      for (const prop in data.columnFields) {
        obj[data.columnFields[props]] = element;
      }
    }
    processDataSet.push(obj);
  });

  return processDataSet;
}

This is giving me the following output which is not what I am looking for:

const output = [
  {
    FieldValue1: 'value33',
    FieldValue2: 'value33',
    FieldValue3: 'value33',
  },
  {
    FieldValue1: 'value33',
    FieldValue2: 'value33',
    FieldValue3: 'value33',
  },
];

It is as expected because every time it is overriding the value and ends with the last value. Please help me with the direction of the code by which I can simultaneously assign the individual value in the loop.


Solution

    • Using Object#values on columnFields, you can get the list of keys to be used in the resulting array of objects
    • Using Array#map, iterate over dataSets
    • In every iteration, use Object#values to get the list of values of the current object. Using Array#reduce, iterate over the latter to create an object with the keys computed at first and current values

    const data = {
      columnFields: { columnField1: 'FieldValue1', columnField2: 'FieldValue2', columnField3: 'FieldValue3' },
      dataSets: [
        { columnProp1: 'value1', columnProp2: 'value2', columnProp3: 'value3' },
        { columnProp1: 'value11', columnProp2: 'value22', columnProp3: 'value33' }
      ]
    };
    
    const { columnFields, dataSets } = data;
    const keys = Object.values(columnFields);
    const res = dataSets.map(e => 
      Object.values(e).reduce((acc, value, index) => ({
        ...acc,
        [keys[index]]: value
      }), {})
    );
    
    console.log(res);