0

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

5 Answers 5

1

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)

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

Comments

0

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

Comments

0

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)

Comments

0

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

Comments

0

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 , []))

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.