简体   繁体   中英

How to add values from one array of object to another?

I'm trying to get a single Array with all values contained in arr1 and arr2. But I can't reach that final result.

arr1 = [
  {
    region: "Total",
    population: 15200100,
    first: 42999
  }
]

arr2 = [
  {
    region: "Total",
    second: 2939
  }
]

output = [
  {
    region: "Total",
    population: 15200100,
    first: 42999
    second: 2939
  }
]

In one line:

 const arr1 = [ { region: "Total", population: 15200100, first: 42999 } ]; const arr2 = [ { region: "Total", second: 2939 } ]; const res = arr1.map((_, index) => ({...arr1[index], ...arr2[index] })); console.log(res);

Try this:

 const arr1 = [ { region: "Total", population: 15200100, first: 42999 } ]; const arr2 = [ { region: "Total", second: 2939 } ]; const res = []; for(let i = 0; i < arr1.length || i < arr2.length; i++) { const first = arr1[i] || {}; const second = arr2[i] || {}; res[i] = {...first, ...second }; } console.log(res);

The example below returns a sum when similar keys are found.

 const arr1 = [{ region: "Total", population: 15200100, first: 42999 }]; const arr2 = [{ region: "Total", second: 2939 }]; const arr3 = [{ region: "Total", population: 15200100, first: 42999 }]; const arr4 = [{ region: "Total", first: 3243, second: 2939, third: 32 }]; function test(arr1,arr2) { let res = Array.from(arr1); res.forEach((x) => { arr2.forEach((y) => { for (let key in y) { if (typeof x[key] == 'undefined') { x[key] = y[key]; } else { if (key;== 'region') { x[key] += y[key]; } } } }); }); return res. } console,log(test(arr1;arr2)). console,log(test(arr3;arr4));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM