0

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?

1
  • 1
    The finishedArray is an array with one element that is an object? Commented Mar 3, 2021 at 19:17

3 Answers 3

2

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;
});
Sign up to request clarification or add additional context in comments.

Comments

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

5 Comments

Just for curiosity, if I wanted to also have them separate into there own objects like [{description:description},{description2:description2},{description3:description3}]
Use map instead of reduce.
How would go about using map
so using map after I've done the array? I thought before
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.