1

Im new in JS and I hope you help me) I need to transform array of objects in this way:

const arr = [
  {id: 'key1', value: 1 },
  {id: 'key2', value: [1,2,3,4]}
 ...
]
const transformedArr = [
   {key1: 1},
   {key2: 1},
   {key2: 2},
   {key2: 3},
   {key2: 4},
   ....
 ]

How can I do it?

3 Answers 3

3

Since you are new to JS ..

Good Old JS with for loops might be easy for you to understand

const arr = [
  {id: 'key1', value: 1 },
  {id: 'key2', value: [1,2,3,4]}
]

const transformedArr  =[]


for(var i = 0 ; i < (arr.length); i++){

   var valArr = arr[i].value

   if( Array.isArray(valArr) ){ // to check if the value part is an array

      for(var j=0 ; j < valArr.length ; j++){

        transformedArr.push({id: arr[i].id,value:valArr[j] })

      }

   }else{

     transformedArr.push({id: arr[i].id,value:valArr })

   }

}

console.log(transformedArr)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use ES6 spread syntax ... with map() method.

const arr = [
  {id: 'key1', value: 1 },
  {id: 'key2', value: [1,2,3,4]}
]

var result = [].concat(...arr.map(({id, value}) => {
  return Array.isArray(value) ? value.map(e => ({[id]: e})) : {[id]: value}
}))

console.log(result)

You can also use reduce() instead of map() method.

const arr = [
  {id: 'key1', value: 1 },
  {id: 'key2', value: [1,2,3,4]}
]

var result = arr.reduce(function(r, {id, value}) {
  r = r.concat(Array.isArray(value) ? value.map(e => ({[id]: e})) : {[id]: value})
  return r;
}, [])

console.log(result)

Comments

0

This proposal features Array.concat, because it add items without array and arrays to an array.

const
    array = [{ id: 'key1', value: 1 }, { id: 'key2', value: [1, 2, 3, 4] }],
    result = array.reduce(
        (r, a) => r.concat(
            [].concat(a.value).map(
                v => ({ [a.id]: v })
            )
        ),
        []
    );
      
console.log(result);

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.