Home > Software engineering >  Iterate an array of objects
Iterate an array of objects

Time:07-09

I have an array of objects.

myArray = [{a:1,b:1,c:1,d:1},{a:2,b:2,c:2,d:2},{a:3,b:3,c:3,d:3},{a:4,b:4,c:4,d:4}]

I want to create a new dictionary from it: newDict = {a:[1,2,3,4],c:[1,2,3,4]}

I'm totally new to Javascript and Node.js Any kind of help is highly appreciated. Thanks in advance.

CodePudding user response:

Alternatively you can also do it in a for loop, in case you are unfamiliar with the reduce method.

const myArray = [{a:1,b:1,c:1,d:1},{a:2,b:2,c:2,d:2},{a:3,b:3,c:3,d:3},{a:4,b:4,c:4,d:4}]

const wantedProperties = ['a', 'b', 'd']

const mydict = {}
for (const item of myArray) {
  for (const [key, value] of Object.entries(item)) {
    if (wantedProperties.includes(key)) {
     mydict[key] = (mydict[key] || []).concat(value)
    }
  }
}

console.log(mydict)

CodePudding user response:

You basically want to group something. For grouping you can usually use .reduce()

On every iteration you iterate over your object entries with Object.entries() and then you always check if your previous value already has that key, if yes, you push it, if not, you create a new array and put your value inside of it.

let myArray = [{a:1,b:1,c:1,d:1},{a:2,b:2,c:2,d:2},{a:3,b:3,c:3,d:3},{a:4,b:4,c:4,d:4}]


let result = myArray.reduce((prev, curr) => {
   Object.entries(curr).forEach(([key, value]) => {
      if(prev[key]) {
         prev[key].push(value)
      } else {
         prev[key] = [value]
      }
   })
   return prev;
}, {})


console.log(result);

CodePudding user response:

let targetArray = [{a:1,b:1,c:1,d:1},{a:2,b:2,c:2,d:2},{a:3,b:3,c:3,d:3},{a:4,b:4,c:4,d:4}]


let result = targetArray.reduce((accc, curr) => {
   Object.entries(curr).forEach(([key, value]) => {
      if(!accc[key]) {
         accc[key] = [value]
      } else {
         accc[key].push(value)
      }
   })
   return accc;
}, {})


console.log(result);

CodePudding user response:

You could take an object with wanted properties and iterate the array by checking the keys of the object. If a key is in the result object, push the value.

const
    data = [{ a: 1, b: 1, c: 1, d: 1 }, { a: 2, b: 2, c: 2, d: 2 }, { a: 3, b: 3, c: 3, d: 3 }, { a: 4, b: 4, c: 4, d: 4 }],
    result = data.reduce((r, o) => {
        Object.entries(o).forEach(([k, v]) => {
            if (k in r) r[k].push(v);
        });
        return r;
    }, { a: [], c: [] });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

One can give keys as params to find the desired result

var myArray = [{ a: 1, b: 1, c: 1, d: 1 }, { a: 2, b: 2, c: 2, d: 2 }, { a: 3, b: 3, c: 3, d: 3 }, { a: 4, b: 4, c: 4, d: 4 }];
function findValues(keysArray) {
    let result = {};
    myArray.forEach((item) => {
        for (var key in item) {
            if (keysArray.includes(key)) {
                if (result[key]) {
                    result[key].push(item[key])
                } else {
                    result[key] = [item[key]];
                }
            }
        }
    });
    return result;
}
console.log(findValues(['a', 'c']));

CodePudding user response:

  1. Create an output object, and iterate over the data
  2. For every object get its Object.entries - this provides us with an array of key/value pairs which we can also iterate over.
  3. Assign an empty array to an output object key if it doesn't exist, then push the corresponding key from the iterated object into it.

const data = [{a:1,b:1,c:1,d:1,z:3},{a:2,b:2,c:2,d:2},{a:3,b:3,c:3,d:3},{a:4,b:4,c:4,d:4,z:12}];

const out = {};

for (const obj of data) {
  const entries = Object.entries(obj);
  for (const [key, value] of entries) {
    out[key] ??= [];
    out[key].push(value);
  };
}

console.log(out);

  • Related