-1

First I'm a newbie to JS... now I have an array with some weird data like below;

var data = [

[21062,5000,0.1,0.2,0.3,0.4,0.5],

[21063,6000,0.11,0.21,0.32,0.45,0.51]

]

I need to create a key name for every comma separator with it's value and present it as a object inside an array

Expected output :

data: [
{"productId" : "21062",
 "amount" : "5000",
 "tax1" : "0.1",
 "tax2" : "0.2",
 "tax3" : "0.3",
 "tax4" : "0.4",
 "tax1" : "0.5"
},

{"productId" : "21063",
 "amount" : "6000",
 "tax1" : "0.11",
 "tax2" : "0.21",
 "tax3" : "0.32",
 "tax4" : "0.45",
 "tax1" : "0.51"
}
]
2
  • 2
    Your expected output is invalid. You have duplicate keys. Commented May 19, 2020 at 5:50
  • Have you tried anything? Please share a minimal reproducible example if you have, otherwise give it a shot yourself first, then post the code you're stuck on. See How to Ask and thanks. Commented May 19, 2020 at 5:51

1 Answer 1

1

You could achieve it with a combination of .map and .forEach

var data = [
  [21062, 5000, 0.1, 0.2, 0.3, 0.4, 0.5],
  [21063, 6000, 0.11, 0.21, 0.32, 0.45, 0.51]
]

let obj = data.map(arr=>{
  let o = {
      productId:arr[0],
      amount:arr[1]
  }
  arr.forEach((e,i)=>{
    if (i > 1){
      o[`tax${i-1}`] = e;
    }
  })
  return o;
})
console.log(obj);

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

1 Comment

excellent, this is what I need..thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.