-1

I have an array of objects with a string value in it, with a first array as an header:

var data = [{records : "productId*amount*tax1*tax2*tax3"},
            {records : "111*2000*10*12*13"},
            {records : "113*3000*10**"}]

I need to convert this array of objects into an individual objects with key-value pairs by using the data[0] as key and rest of the data[x] as its value .

Expected output :

data: [
  {
     "productId" : "111",
     "amount" : '2000",
     "tax1" : "10",
     "tax2" : "12",
     "tax3" : "13"
  },
  {
     "productId" : "113",
     "amount" : "3000",
     "tax1" : "10",
     "tax2" : "0",
     "tax3" : "0"
  }
]

I can use the split operator to split the strings and get them as an individual array, but can't figure out how to assign it to key value pairs in an array and I'm very new to JS.

Mar1009
  • 721
  • 1
  • 11
  • 27

2 Answers2

1

You can use Object.fromEntries in combination with normal iteration methods, like .map:

let data = [{records : "productId*amount*tax1*tax2*tax3"},
            {records : "111*2000*10*12*13"},
            {records : "113*3000*10**"}];

let [fields, ...rows] = data.map(({records}) => records.split("*"));
let result = rows.map(values => 
    Object.fromEntries(values.map((value, i) => [fields[i], value]))
);
console.log(result);
trincot
  • 317,000
  • 35
  • 244
  • 286
1

So you split the first index into the keys.

You loop over the remaining and generate the objects using the key for the index.

var data = [{
    records: "productId*amount*tax1*tax2*tax3"
  },
  {
    records: "111*2000*10*12*13"
  },
  {
    records: "113*3000*10**"
  }
]

// grab the keys from first record
var keys = data.shift().records.split("*")

// loop over the rest of the records
var result = data.reduce(function(arr, item) {
  // split up the records
  const rec = item.records.split("*").reduce(function(obj, value, index) {
    // grab the key for the index
    var key = keys[index]
    // set the object with the key and the value
    obj[key] = value
    // return back the updated object
    return obj
  }, {})
  // add the object to the array
  arr.push(rec)
  return arr
}, [])
console.log(result);
epascarello
  • 204,599
  • 20
  • 195
  • 236