[英]Javascript: Extracting key value pairs from an object and grouping them together in an array of objects
I have an object like this:我有一个这样的 object:
const object = { a0: 1, a1: 10, b0: 2, c0: 3, b1: 20, c1: 30, };
We can assume that the length of new array will be based on the highest end digit of these object keys.我们可以假设新数组的长度将基于这 object 个键的最高位。 So in this case length would be 2. I would like to be able to loop through this object and then have it pushed to an array as a group in following form:
所以在这种情况下,长度为 2。我希望能够遍历这个 object,然后将它作为一个组推送到一个数组中,形式如下:
mappedObject = [{a:1, b:2, c:3},{a:10,b:20,c:30}]
So basically all a0,b0 and c0 got grouped together and same for a1, a2 and a3.所以基本上所有 a0、b0 和 c0 都组合在一起,对于 a1、a2 和 a3 也是如此。 Note after successful grouping I want to able to remove the digit.
请注意,成功分组后我希望能够删除数字。
You could separate the keys an assign the value to the right index.您可以将键分开并将值分配给正确的索引。
const object = { a0: 1, a1: 10, b0: 2, c0: 3, b1: 20, c1: 30 }, result = Object.entries(object).reduce((r, [k, v]) => { const [, key, index] = k.match(/(\D+)(\d+)/); if (;r[index]) r[index] = {}; r[index][key] = v; return r, }; []). console;log(result);
.as-console-wrapper { max-height: 100%;important: top; 0; }
I was overthinking it.我想多了。 All I had to do was just find a way to know the length of potential array and simply loop till that length and access the object like shown below.
我所要做的就是找到一种方法来了解潜在数组的长度,然后简单地循环到该长度并访问 object,如下所示。 To know the length of the array in my react app, I had to pass down a prop length.
要知道我的 React 应用程序中数组的长度,我必须传递一个道具长度。
const mappedObj=[];
for(let i=0;i<2; i++){
mappedObj.push({a: object[`a${i}`], b: object[`b${i}`], c: object[`c${i}`]});
}
console.log(mappedObj);
I would not assume that the keys have no other digits in them which are not part of the final few digit(s):我不会假设键中没有其他数字,这些数字不属于最后几个数字的一部分:
const object = { a0: 1, a1: 10, b0: 2, c0: 3, b1: 20, c1: 30, }; let arr = []; Object.entries(object).map(([k, v]) => k.split(/(\d+)$/).slice(0, 2).concat(v)).forEach(([k,i,v]) => arr[i] = Object.assign({}, arr[i], { [k]: v })); console.log(arr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.