skip to Main Content

Assuming we have the following array structure of n length:

const sourceArray = [
  { "dynamicKey1": true },
  { "dynamicKey2": false },
  { "dynamicKey3": true },
  ...
]

How could I tersely reduce this array to a single object of dynamic length:

const convertedObj = {
  "dynamicKey1": true,
  "dynamicKey2": false,
  "dynamicKey3": true
  ...
}

Thanks!

3

Answers


  1. Use reduce and ... to spread the object in array.

    const sourceArray = [{ dynamicKey1: true }, { dynamicKey2: false }, { dynamicKey3: true }];
    
    const convertedObj = sourceArray.reduce((acc, _) => ({ ...acc, ..._ }), {});
    
    console.log(convertedObj);
    Login or Signup to reply.
  2. You can achieve this using Array.prototype.reduce() and Object.assign() to merge curr into acc (starts of as {} initially), copying the key-value pairs.:

    const sourceArray = [
      { "dynamicKey1": true },
      { "dynamicKey2": false },
      { "dynamicKey3": true }
    ];
    const convertedObj = sourceArray.reduce((acc, curr) => Object.assign(acc, curr), {});
    console.log(convertedObj);
    Login or Signup to reply.
  3. const sourceArray = [
      { "dynamicKey1": true },
      { "dynamicKey2": false },
      { "dynamicKey3": true }
    ]
    
    const convertedObj = {};
    
    sourceArray.forEach((v, i) => {for(let key in v){convertedObj[key]= v[key]}});
    
    convertedObj
    
    {"dynamicKey1": true, "dynamicKey2": false, "dynamicKey3": true}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search