Oliver
Oliver

Reputation: 382

React - How to convert a nested object into a array

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

Upvotes: 0

Views: 807

Answers (5)

jsBug
jsBug

Reputation: 355

we can achieve this way too

const obj = {
   comedy: ['book1', 'book2'],
   action: ['book3', 'book4'],
   drama: ['book5'],
}
const fun  = (ar, temp)=>{
  for(x in ar){
    ar[x].map((e, i)=> {
      var data = {[x] : e}
     temp.push(data)
    })}
     return temp
}
console.log(fun(obj , []))

Upvotes: 0

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27192

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

Upvotes: 0

Nick
Nick

Reputation: 147146

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)

Upvotes: 1

Obie
Obie

Reputation: 302

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

Upvotes: 0

user3335966
user3335966

Reputation: 2745

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)

Upvotes: 0

Related Questions