Search code examples
javascriptarraysobjectjavascript-objects

how to add objects to arrays


I'm trying to construct an array of objects from a set of two different arrays. I'm a little comfussed on where I need to go from here.

I'm creating a unique key value, but the object is going into the array individual.

const startingArray = [
{
 key: "description",
 value: "my description"
},
{
 key: "description2",
 value: "my description2"
},
{
 key: "description3",
 value: "my description3"
},
]

my logic

const k = mystartingArray.reduce((acc, d, count) => {
 const name = Object.value(d)[0]
 const title = Object.value(d)[1]

const value = {
 [name]: title
}
acc.push(value)

return acc

},[])

how I want the Array to look

const finishedArray = [
{
   description: "my description",
   description2: "my description2,
   description3: "my description3,
}

How far am I off?


Solution

  • I think this would be simpler to solve just by using a basic forEach.

    let value = {};
    
    startingArray.forEach(obj => {
        value[obj.key] = obj.value;
    });
    
    const finishedArray = [value];
    

    Or, if you don't want to have a value object:

    const finishedArray = [{}];
    
    startingArray.forEach(obj => {
      finishedArray[0][obj.key] = obj.value;
    });