0

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I didn't understand it very well but ty anyway.
Basically I loop through each item of the array, I then isolate ts and put all of the other keys and values in the rest variable. I then loop through rest and put the values in the array corresponding to the key.
@DevM I've added comments. This solution is dynamic and allows you not to hard-code an array of keys
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.