0

I have an array of object as below.

data: [ {col: ['amb', 1, 2],} , {col: ['bfg', 3, 4], },]

From above, I need to get array of array as below.

[ [{a: 'amb',b: [1], c: 'red'}, {a: 'amb',b: [2], c: 'orange'}], 
  [{a: 'bfg',b: [3], c: 'red'}, {a: 'bfg',b: [4], c: 'orange'}] 
]

My attempt is as below.

let arrInner: Array<any> = []
let arrOuter: Array<Array<any>> = []

_.forEach(data, (item, i) => {
    //create two objects redObj and orangeObj

    redObj = {
      a: item.col[0].toString(),
      b: [item.col[1] as number],
      c: 'red'
    }
    orangeObj = {
      a: item.col[0].toString(),
      b: [item.col[2] as number],
      c: 'orange'
    }
    
    //put those two objects to array
    arrInner.push(redObj)
    arrInner.push(orangeObj)
    
    //assign that array to another array
    arrOuter[i] = arrInner
})

But when I print the arrOuter, it is not my expected output. Where I was wrong and how can I fix this?

3
  • Array<any> is not JavaScript. Is this TypeScript? Commented Jul 1, 2021 at 19:38
  • "Where I was wrong and how can I fix this?" I suggest that you add console.log() to see what is happening in your code to figure out what is wrong. You might want to rethink your entire approach, though. If I were solving this, I would break it into smaller pieces. For example, I would start with ['amb', 1, 2] and convert it into [{a: 'amb',b: [1]}, {a: 'amb',b: [2]}]. Don't try to eat the entire elephant at once. Commented Jul 1, 2021 at 19:42
  • 1
    You also might want to look into the map() function instead of forEach(). Commented Jul 1, 2021 at 19:43

1 Answer 1

1

You need to create a new arrInner each time through the forEach loop. Then push that onto arrOuter.

let arrOuter: Array <Array <any>> = []

_.forEach(data, (item, i) => {

  //create two objects redObj and orangeObj

  redObj = {
    a: item.col[0].toString(),
    b: [item.col[1] as number],
    c: 'red'
  }
  orangeObj = {
    a: item.col[0].toString(),
    b: [item.col[2] as number],
    c: 'orange'
  }

  //put those two objects to array
  let arrInner = [redObj, orangeObj]

  //assign that array to another array
  arrOuter.push(arrInner)
})

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

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.