Home > database >  Converting an array of array to a single array of object
Converting an array of array to a single array of object

Time:06-22

I have a data structure that looks like this:

 let a = [
      ["base-certificate", 60, 3, 2022],
      ["case-certificate", 1, 3, 2022],
      ["standard-certificate", 7, 3, 2022],
    ];

I want to transform it to look like this:

[{x:[3, 2022], base: 60, case:1, standard: 7}]

I tried using the map method on the array like:

let a = [
  ["base-certificate", 60, 3, 2022],
  ["case-certificate", 1, 3, 2022],
  ["standard-certificate", 7, 3, 2022],
];

let result = a.map((elem) => {
  let obj = {};
  elem.forEach((e, i) => {
    obj["x"] = [e[2], e[3]];
    obj[e[0]] = e[1];
  });
  return obj;
});
console.log(result);

The code above did not get the desired output. what is the best way to go about this?

CodePudding user response:

You don't need both the map and the forEach, you can remove the outer map.

Also if you want to remove the "-certificate" part, you can use a split.

Something like this should work

let a = [
  ["base-certificate", 60, 3, 2022],
  ["case-certificate", 1, 3, 2022],
  ["standard-certificate", 7, 3, 2022],
];

let obj = {};
a.forEach((e, i) => {
  obj["x"] = [e[2], e[3]];
  obj[e[0].split('-')[0]] = e[1];
});

console.log(obj);

CodePudding user response:

map() is for creating an array. You just want one object, you should declare it outside the loop and use forEach() to fill it in. You don't need nested loops.

You can use replace() to remove -certificate from the names.

let a = [
  ["base-certificate", 60, 3, 2022],
  ["case-certificate", 1, 3, 2022],
  ["standard-certificate", 7, 3, 2022],
];

let obj = {};

a.forEach((e, i) => {
  obj["x"] = [e[2], e[3]];
  obj[e[0].replace('-certificate', '')] = e[1];
});

console.log(obj);

CodePudding user response:

let a = [
  ["base-certificate", 60, 3, 2022],
  ["case-certificate", 1, 3, 2022],
  ["standard-certificate", 7, 3, 2022],
];

let obj = {};
a.forEach((e) => {
    obj["x"] = [e[2], e[3]];
    obj[e[0].replace('-certificate',"")] = e[1];
});
console.log([obj]);

  • Related