1

I want to take an existing array and add it to the existing array of Objects. I want to add a new key with values from reasons. Please help.

Array:

const reasons = ['a', 'b', 'c']; 

Array of objects that look like:

[
    {
        id: 1,
        Data: 'yes',
        active: true
    },

    {
        id: 2,
        Data: 'yes',
        active: false
    },

    {
        id: 3,
        Data: 'data',
        active: false
    }
]

Result want:

[
    {
        id: 1,
        Data: 'yes',
        active: true,
        reason: a
    },

    {
        id: 2,
        Data: 'yes',
        active: false,
        reason: b
    },

    {
        id: 3,
        Data: 'data',
        active: false,
        reason: c
    }
]
1
  • Yes, sorry! I got it mixed up. I have already tried to create a key but obviously cannot have same existing keys in an object.. with the array. I just have no idea how to approach this. Commented Sep 27, 2024 at 1:01

3 Answers 3

2

You can achieve this by mapping over your existing array of objects and adding the values from the reasons array to each object. Here's a simple way to do this in JavaScript:

Example:

const reasons = ['a', 'b', 'c'];

const data = [
  { id: 1, Data: 'yes', active: true },
  { id: 2, Data: 'yes', active: false },
  { id: 3, Data: 'data', active: false }
];

const result = data.map((item, index) => {
  return {
    ...item,
    reason: reasons[index]
  };
});

console.log(result);

Output:

[
  { id: 1, Data: 'yes', active: true, reason: 'a' },
  { id: 2, Data: 'yes', active: false, reason: 'b' },
  { id: 3, Data: 'data', active: false, reason: 'c' }
]
Sign up to request clarification or add additional context in comments.

Comments

1

A simple map function can accomplish this for you.

const reasons = ['a', 'b', 'c'];

const obj = [
  {id: 1, Data: 'yes', active: true},
  {id: 2, Data: 'yes', active: false},
  {id: 3, Data: 'data', active: false}
];

const merged = obj.map((reason, index) => {
  // .reason is your new key, and it gets it from reasons[index]
  reason.reason = reasons[index];
  return reason;
});

The new value of merged:

[
  { id: 1, Data: 'yes', active: true, reason: 'a' },
  { id: 2, Data: 'yes', active: false, reason: 'b' },
  { id: 3, Data: 'data', active: false, reason: 'c' }
]

I hope that's what you were going for and that this helped.

Comments

1

Simplest way is to loop through each object and add reason to it

const reasons = ['a', 'b', 'c']
const objects = 
[
    {
        id: 1,
        Data: 'yes',
        active: true
    },

    {
        id: 2,
        Data: 'yes',
        active: false
    },

    {
        id: 3,
        Data: 'data',
        active: false
    }
]
const result = objects.map((obj, i)=> ({...obj, reason : reasons[i]}))
console.log(result)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.