Home > Software engineering >  Looping array of object into array of object javascript
Looping array of object into array of object javascript

Time:10-24

so i have two arrays of object like this:

var lab =[
  { label: '1', value: 42 },
  { label: '2', value: 55 },
  { label: '3', value: 51 },
  { label: '4', value: 22 } 
  ];
  
  
var val = [ { label: '1', value: 42 },
  { label: '2', value: 55 },
   ];

lab.forEach(labs=>{
    val.forEach(vals=>{
        labs["columns"]=vals.value
    })
})
console.log(lab)

i try to get the value like this

[ { label: '1', value: 42, columns: {42,55} },
  { label: '2', value: 55, columns:{42,55} },
  { label: '3', value: 51, columns: {42,55} },
  { label: '4', value: 22, columns: {42,55} } ]

but after i ran the code i get the value that i am not wanted like this:

[ { label: '1', value: 42, columns: 55 },
  { label: '2', value: 55, columns: 55 },
  { label: '3', value: 51, columns: 55 },
  { label: '4', value: 22, columns: 55 } ]

where do i did wrong actually on the loop..

CodePudding user response:

Does this do what you want?

const lab = [
  { label: '1', value: 42 },
  { label: '2', value: 55 },
  { label: '3', value: 51 },
  { label: '4', value: 22 },
];
const val = [
  { label: '1', value: 42 },
  { label: '2', value: 55 },
];

// we get an array of stuff that the OP wants to add,
// as apparently it is identical for each object.
const columns = val.map(obj => obj.value);

const a = lab.map(labs => {
  return {
    // shallow copys for every item.
    ...labs,
    columns: [...columns],
  };
});

console.log({ a });
.as-console-wrapper { min-height: 100%!important; top: 0; }

map array method takes a function returns a new array where each element was updated by calling that function with element as it's argument.

This answer uses two calls of map, same amount as your answer, however in your answer map calls are nested, so the inner map would be called for each element, while it's result will be always the same, in my answer we call it once.

CodePudding user response:

i have figured it out by using map function

var lab =[
  { label: '1', value: 42 },
  { label: '2', value: 55 },
  { label: '3', value: 51 },
  { label: '4', value: 22 } 
  ];




var val = [ { label: '1', value: 10 },
  { label: '2', value: 55 },
   ];

const a = lab.map((labs)=>{
    let ab={
        label:labs.label,
        value:labs.value,
        columns:val.map((vals)=>{
        return vals.value
    })
    }
    return ab
    
})
console.log(a)

hope it will help

  • Related