skip to Main Content

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’];

Object of arrays 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
}]

3

Answers


  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)
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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' }
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search