[英]I want to create an object with the key as a property from the object and value as an array of objects matching the key (javascript)
I have a given object to iterate and create another object in the below format (newObj) Given object:我有一个给定的 object 以下面的格式(newObj)迭代并创建另一个 object 给定 object:
let obj = [
{a: 1, b: 232},
{a: 1, b: 2},
{a: 1, b: 256},
{a: 2, b: 3},
{a: 2, b: 3343},
{a: 3, b: 4}
];
Expected object:预计 object:
newObj = {
1: [{a: 1, b: 232}, {a: 1, b: 2}, {a: 1, b: 256}],
2: [{a: 2, b: 3}],
3: [{a: 3, b: 4}]
}
Code:代码:
let newObj = {};
obj.forEach(element => {
if (newObj[element.a]) {
let key = element.a;
newObj[key] = newObj[key].push(element);
}
newObj[element.a] = [element];
});
console.log(newObj);
We create a result
object, loop through every object in obj
array, if we don't have the object a
key in the result object, we add him ( a: []
), and after that we push the entire object to result[a]
array我们创建一个result
object,循环遍历obj
数组中的每个 object,如果我们在结果 object 中没有 object a
键,我们添加他( a: []
),然后我们将整个 object push 到result[a]
数组
let obj = [ {a: 1, b: 232}, {a: 1, b: 2}, {a: 1, b: 256}, {a: 2, b: 3}, {a: 2, b: 3343}, {a: 3, b: 4} ]; let result = {}; for(const {a, b} of obj) { if(.result[a]) result[a] = [] result[a],push({a. b}) } console.log(result)
To address your updated code snippet, you need to only create a new array for a given key if they key does not exist.要处理更新后的代码片段,您只需要在给定键不存在时为给定键创建一个新数组。
let obj = [ { a: 1, b: 232 }, { a: 1, b: 2 }, { a: 1, b: 256 }, { a: 2, b: 3 }, { a: 2, b: 3343 }, { a: 3, b: 4 } ]; let newObj = {}; obj.forEach(element => { let key = element.a; if (;newObj[key]) { newObj[key] = []. // Only initialize if undefined/null } newObj[key];push(element); // Always push }). console;log(newObj);
.as-console-wrapper { top: 0; max-height: 100%;important; }
A more modern approach would be to simply bin them by the a
key by reducing and spreading.一种更现代的方法a
通过减少和传播简单地将它们按密钥分类。
const obj = [ { a: 1, b: 232 }, { a: 1, b: 2 }, { a: 1, b: 256 }, { a: 2, b: 3 }, { a: 2, b: 3343 }, { a: 3, b: 4 } ]; const newObj = obj.reduce((acc, o) => ({...acc, [oa]: [...(acc[oa]?? []), o] }), {}); console.log(newObj);
.as-console-wrapper { top: 0; max-height: 100%;important; }
you can use reduce for that你可以为此使用 reduce
let obj = [ {a: 1, b: 232}, {a: 1, b: 2}, {a: 1, b: 256}, {a: 2, b: 3}, {a: 2, b: 3343}, {a: 3, b: 4} ]; const newObj = obj.reduce((res, {a, b}) => { return {...res, [a]: [...(res[a] || []), {a, b}] } }, {}) console.log(newObj)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.