javascript - 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
解决方案
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);
推荐阅读
- splunk - Splunk 如何组合两个查询并得到一个答案
- java - 使用 Pattern & Matcher 的所有重叠模式的索引
- python - 形成正则表达式模式的麻烦。
- tcl - 使用返回的数组
- apache-kafka-streams - Kafka 流 - 仅一次配置
- google-maps - 如何在谷歌地图api中用折线显示方向点?(未捕获的 ReferenceError:未定义 google)
- python - 无法在我的 Linux 测试服务器上安装任何软件包
- java - 如何模拟公共 API(第三方 API)来生成 spring restdocs
- java - 创建支持不同屏幕尺寸的相同 UI?
- javascript - 如何将参数传递给 addEventListener 中的外部函数