How to add values to keys inside an object in an array from other array in javascript

Viewed 71

I have an array like below I am trying to add some value by replacing null inside the object inside the array. The values I wanted to add is from different array "y"

let toBesubmitted = [
        {a: null, id: "a"},
        {b: null, id: "b"},
        {c: null, id: "c"},
        {d: null, id: "d"},
        {e: null, id: "e"}
      ]

Another array

let y= ["apple", "ball", "cat", "dog", "elephant"]

How can I achieve this?

6 Answers

You can do that by using a forEach loop on the array and assigning a value to the item[item.id] property at a specific index of the y array:

let toBesubmitted = [
        {a: null, id: "a"},
        {b: null, id: "b"},
        {c: null, id: "c"},
        {d: null, id: "d"},
        {e: null, id: "e"}
      ]

let y= ["apple", "ball", "cat", "dog", "elephant"]

toBesubmitted.forEach((item, index) => item[item.id] = y[index]||null);

console.log(toBesubmitted)

A simple loop would do it, if toBeSubmitted[0].a should be y[0] and the id property tells us which property to set:

for (let i = 0; i < toBesubmitted.length; ++i) {
    toBesubmitted[i][toBesubmitted[i].id] = y[i];
}

Example:

let toBesubmitted = [
    {a: null, id: "a"},
    {b: null, id: "b"},
    {c: null, id: "c"},
    {d: null, id: "d"},
    {e: null, id: "e"}
];

let y = ["apple", "ball", "cat", "dog", "elephant"];

for (let i = 0; i < toBesubmitted.length; ++i) {
    toBesubmitted[i][toBesubmitted[i].id] = y[i];
}

console.log(toBesubmitted);

This is not the best answer though but try this:

    //print object
toBesubmitted.forEach(function(element, key){
    for(let e in element){
        if(e == Object.keys(element)[0])
            element[e] = y[key];
    }
});
Console.log(toBesubmitted);

Assuming toBesubmitted[index][key] is y[index][0] This answer doesn't rely on index being in a particular order.

let toBesubmitted = [
  { a: null, id: "a" },
  { b: null, id: "b" },
  { c: null, id: "c" },
  { d: null, id: "d" },
  { e: null, id: "e" }
];

let y= ["apple", "ball", "cat", "dog", "elephant"];

y.forEach( c => {
  const prop = toBesubmitted.find(tbs => tbs.id === c[0]);
  if(prop){
    prop[c[0]] = c;
  }
});

You can also use reduce function like below;

let toBesubmitted = [
{a: null, id: "a"},
{b: null, id: "b"},
{c: null, id: "c"},
{d: null, id: "d"},
{e: null, id: "e"}
];

let y = ["apple", "ball", "cat", "dog", "elephant"];

toBesubmitted.reduce( (acc,curr,idx) => curr[curr.id] = y[idx], {} );

console.log(toBesubmitted);

EDITED

let toBesubmitted = [
    {a: null, id: "a"},
    {b: null, id: "b"},
    {c: null, id: "c"},
    {d: null, id: "d"},
    {e: null, id: "e"}
]

let y= ["apple", "ball", "cat", "dog", "elephant"]

toBesubmitted.forEach((item, index) => {
    Object.keys(item).forEach(key => {
        if (item[key] === null) {
            item[key] = y[index];
        }
    })
})

console.log(toBesubmitted);

Related