[英]Get all the children objects key into new array of objects using reduce
[英]Make a new array with all the similar key values from previous array using .reduce()
我怎样才能转动阵列:
data = [
{key1: a, key2: 1},
{key1: b, key2: 2},
{key1: c, key2: 3}]
进入数组:
newArray = [1, 2, 3]
使用减少?
您不想减少(将数组转换为单个元素)但您尝试映射(将数组转换为另一个数组)
data = [ {key1: 'a', key2: 1}, {key1: 'b', key2: 2}, {key1: 'c', key2: 3} ] console.log(data.map(el => el.key2))
我不知道你真正想要什么,但是如果你想用 reduce 对象中特定键的值创建一个新数组,你可以看到你的例子,你可以这样做:
const data = [
{key1: "a", key2: 1},
{key1: "b", key2: 2},
{key1: "c", key2: 3}
];
const ans = data.reduce((prev, curr) => {
prev.push(curr.key2);
return prev;
}, []); // start with empty array
// ans: [ 1, 2, 3 ]
但是,如果您想将一组新数组中的所有键分开,您可以这样做:
const data = [
{key1: "a", key2: 1},
{key1: "b", key2: 2},
{key1: "c", key2: 3}
];
const ans = data.reduce((prev, curr) => {
Object.keys(curr).forEach((key) => {
if (!prev[key]) {
prev[key] = [curr[key]];
} else {
prev[key].push(curr[key]);
}
});
return prev;
}, {}); // start with empty object
// ans: { key1: [ 'a', 'b', 'c' ], key2: [ 1, 2, 3 ] }
作为我的建议,我更喜欢使用for..of比reduce
或forEach
或map
更干净、更快
两者的例子:
// Example 1:
const ans = [];
for (const obj of data) {
ans.push(obj.key2);
}
// ans: [ 1, 2, 3 ]
// Example 2:
const ans = {};
for (const obj of data) {
for (const key of Object.keys(obj)) {
if (!ans[key]) {
ans[key] = [obj[key]];
} else {
ans[key].push(obj[key]);
}
}
}
// ans: { key1: [ 'a', 'b', 'c' ], key2: [ 1, 2, 3 ] }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.