Skip to content Skip to sidebar Skip to footer

Restructuring An Array Into A List Of Objects In A Object Javascript/nodejs

My desired output is at the bottom of this post, I want to remove the array and put a list of objects inside an object. I'm sharing my map function because i'm hopeful that there's

Solution 1:

Array.prototype.map() will return an array. You probably want to use Array.prototype.reduce(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

I think this gives you your desired output

const dynamictaskdetails = [
  {
    name: '0000x0000',
    filepath: 'D:\\Code\\ImageTiling\\6\\0000x0000.png'
  },
  {
    name: '0000x0001',
    filepath: 'D:\\Code\\ImageTiling\\6\\0000x0001.png'
  },
  {
    name: '0000x0002',
    filepath: 'D:\\Code\\ImageTiling\\6\\0000x0002.png'
  }
];

const taskparamsobj = {
  tr: 16,
  tc: 16,
  ofr: 16,
  ofc: 16,
  outfile: 'D:\\Code\\Process\\1'
};

const taskparamscompiled = dynamictaskdetails.reduce((accumulator, elem) => {
  const taskname = 'process' + elem.name;
  return {
    ...accumulator,
    [taskname]: taskparamsobj,
  };
}, {});

console.log(taskparamscompiled);

This resulted in the following output:

{
  process0000x0000: { tr:16, tc:16, ofr:16, ofc:16, outfile:'D:\\Code\\Process\\1' },
  process0000x0001: { tr:16, tc:16, ofr:16, ofc:16, outfile:'D:\\Code\\Process\\1' },
  process0000x0002: { tr:16, tc:16, ofr:16, ofc:16, outfile:'D:\\Code\\Process\\1' }
}

Post a Comment for "Restructuring An Array Into A List Of Objects In A Object Javascript/nodejs"