简体   繁体   English

map 如何通过动态键从 object 数组中获取值?

[英]How to map get values by dynamic key from array of object?

I want to fetch object values by dynamic key inside map() if possible.如果可能,我想通过map()中的动态键获取 object 值。

 const array = [ { "ts": 1620988054, "KEY1": 14, "KEY2": 23, "KEY3": 58 }, { "ts": 1620901654, "KEY1": 46, "KEY2": 34, "KEY3": 42 }, { "ts": 1620898054, "KEY1": 16, "KEY2": 44, "KEY3": 24 } ]; let data = {}; const arrayOfKeys = [ "KEY1", "KEY2", "KEY3" ]; const keyObject = { "KEY1": "KEY1", "KEY2": "KEY2", "KEY3": "KEY3" }; for (let index = 0; index < arrayOfKeys.length; index++) { const key = Object.keys(keyObject)[index]; data[key] = array.map(({ KEY1 }) => KEY1); data[key] = array.map(({ KEY2 }) => KEY2); data[key] = array.map(({ KEY3 }) => KEY3); } console.log(data);

 const array = [ {"ts":1620988054, "KEY1":14, "KEY2":23, "KEY3":58}, {"ts":1620901654, "KEY1":46, "KEY2":34, "KEY3":42}, {"ts":1620898054, "KEY1":16, "KEY2":44, "KEY3":24}]; const data = array.reduce((acc, cur) => { // loop through array const {ts, ...rest} = cur; // for each item, isolate ts from the rest Object.entries(rest).forEach(([k, v]) => { // loop through the rest if (k in acc) acc[k].push(v) // if we already have an array for the key, push the new value to it else acc[k] = [v]; // else create a new array with that key/value pair }); return acc }, {}); console.log(data);

If you want an object containing keys that correlate with your array of keys, you can reduce the items in the array by reducing over the array, and within the items, reducing the keys.如果您想要一个 object 包含与您的键数组相关的键,您可以通过减少数组和项目内的项目来减少数组中的项目,减少键。

 const array = [ { "ts": 1620988054, "KEY1": 14, "KEY2": 23, "KEY3": 58 }, { "ts": 1620901654, "KEY1": 46, "KEY2": 34, "KEY3": 42 }, { "ts": 1620898054, "KEY1": 16, "KEY2": 44, "KEY3": 24 } ]; const arrayOfKeys = [ "KEY1", "KEY2", "KEY3" ]; const data = array.reduce( (accOuter, record) => arrayOfKeys.reduce((accInner, key) => ({...accInner, [key]: record[key]? [...accInner[key], record[key]]: accInner[key] }), accOuter), Object.fromEntries(arrayOfKeys.map(key => [ key, [] ]))); console.log(data);
 .as-console-wrapper { top: 0; max-height: 100%;important; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM