首页 > 解决方案 > How to push object by following its structure to array of objects

问题描述

Here is my object structure

var obj = {'name':string,'place':string};

Here is another object

var arr = 
{
'a':Alpha,
'b':Australia,
'a_x':Beta,
'b_y':Canada,
'a_3':Charlie,
'b_4':China,
}

I want to push it to the proper object like

var finalArray = [
{'name':Alpha,'place':Australia},
{'name':Beta,'place':Canda},
{'name':Charlie,'place':China}
]

Don't know how to start with the iteration

Please help in this. Thanks in advance

标签: javascriptarraysloopsobjectfor-loop

解决方案


We use Object.values to iterate on the values; and Array.reduce to build up the final array going through the original data.

const arr = {
  a: 'Alpha',
  b: 'Australia',
  a_x: 'Beta',
  b_y: 'Canada',
  a_3: 'Charlie',
  b_4: 'China',
};

const finalArray = Object.values(arr).reduce((tmp, x, xi) => {
  // only treat one on two
  if (!(xi % 2)) return tmp;

  return [
    ...tmp,

    {
      // Get the previous key value
      name: arr[Object.keys(arr)[xi - 1]],

      place: x,
    },
  ];
}, []);

console.log(finalArray);


推荐阅读