简体   繁体   中英

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.

 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.

 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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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