ronoc4
ronoc4

Reputation: 637

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?

Upvotes: 0

Views: 51

Answers (3)

Keimeno
Keimeno

Reputation: 2644

To finish your code:

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

const k = startingArray.reduce((acc, d, count) => {
  return [{
    ...(acc[0] || {}),
    [d.key]: d.value
  }]
},[])

console.log(k);

However, I think the solution of Rocket Hazmat is more reasonable than this.

Upvotes: 1

user9706
user9706

Reputation:

const finishedArray = [
  startingArray.reduce((a, v) => {a[v.key] = v.value; return a}, {})
]

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227200

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;
});

Upvotes: 2

Related Questions