Home > Software engineering >  React - How to convert a nested object into a array
React - How to convert a nested object into a array

Time:09-18

I have the following object that I would like to convert it into an array of object and each object from the array to have the key: value[0].

object:

const obj = {
   comedy: ['book1', 'book2'],
   action: ['book3', 'book4'],
   drama: ['book5'],
}

output

const arr = [
{comedy: 'book1'},
{comedy: 'book2'},
{action: 'book3'},
{action: 'book4'},
{drama: 'book5'},
]

So far I have tried solving this with loops and using Object.entries. But I do not get the output I need.

let result = [];

for(const [key1, value1] of Object.entries(arr)) {
  for (const [key2, value2] of Object.entries(value1)) {
    if(result[key2]) {
      result[key2] [key1] = value2
    } else {
      result[key2] = {[key1]: value2}
    }
  }
}

console.log(result)

I have also tried to loop recalling the function inside itself. (I have found this search for the answer). But it will get stucked in a infinite loop.

const result = [];

const getArray = (obj) => {
  if (!obj) return;

  const {keys, ...rest} = obj;
  result.push({...rest});
  getArray(keys);
}

console.log('here', getArray(arr));

CodePudding user response:

const obj = {
   comedy: ['book1', 'book2'],
   action: ['book3', 'book4'],
   drama: ['book5'],
}

const result = Object
  .keys(obj)
  .reduce((acc, key) => 
    [...acc, ...obj[key]
      .map((value) => ({[key]: value}))],
    []
  )

console.log(result)

CodePudding user response:

Try this


function nestedObjectIntoArray(obj) {
  const arr = [];
  for (const key in obj) {
    for (const value of obj[key]) {
      const obj = {};
      obj[key] = value;
      arr.push(obj);
    }
  }
  return arr;
}

const obj = {
  comedy: ["book1", "book2"],
  action: ["book3", "book4"],
  drama: ["book5"],
};

console.log(nestedObjectIntoArray(obj));

CodePudding user response:

You could use a reduce over the entries of obj, adding objects to the accumulator for each entry in the array value:

const obj = {
  comedy: ['book1', 'book2'],
  action: ['book3', 'book4'],
  drama: ['book5'],
}

const arr = Object.entries(obj)
  .reduce((acc, [k, v]) => acc.concat(v.map(b => ({ [k] : b }))),
  []
  )
  
console.log(arr)

CodePudding user response:

const obj = {
   comedy: ['book1', 'book2'],
   action: ['book3', 'book4'],
   drama: ['book5'],
}

let result = Object.entries(obj).flatMap(([k,v]) => v.map(n => ({[k]:n})) )

console.log(result)

CodePudding user response:

We can also achieve this by just using Array.forEach() method.

Live Demo :

// Input object
const obj = {
   comedy: ['book1', 'book2'],
   action: ['book3', 'book4'],
   drama: ['book5'],
};

// Declare a variable to store the final result.
const arr = [];

// Iterate the input object based on the keys and build the final object.
Object.keys(obj).forEach(key => {
  obj[key].forEach(item => {
    arr.push({ [key]: item })
  })
});

// Result
console.log(arr);

  • Related