0

I would like to know how would I merge this bidimensional array

let arr[
  ['Reference', 'Price'],
  ['232323DD, 15.00]
];

I want to convert this into

[
  {name: 'Reference', value: '232323DD'},
  {name: 'Price', value: 15.00}
]

I've tried this: Convert a two dimensional array into an array of objects but It didn't work for me.

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
Madtin
  • 109
  • 4
  • 12

7 Answers7

1

You can map through the first array in that array and use their values as the keys to an object:

let arr = [
  ['Reference', 'Price'],
  ['232323DD', '15.00']
];

console.log(
  arr[0].map((name, i) => ({name, value:arr[1][i]}))
)

If you are unsure about the size of the two arrays, you should first check whether their lengths are equal, to avoid undefined.

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
1

You can use .map():

let [keys, values] = [
   ['Reference', 'Price'],
   ['232323DD', 15.00]
];

let result = keys.map((k, i) => ({name: k, value: values[i]}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
0

Other solution if you are not familiar with map (I think using map for this example make it a bit hard to read)...

const arr = [
  ['Reference', 'Price'],
  ['232323DD', 15.00]
]

const obj = []
arr.forEach(x => obj.push({name: x[0], value: x[1]}))

console.log(obj)
José Antonio Postigo
  • 2,674
  • 24
  • 17
0

You can use the map function. It will run the callback on each array item, return it in a new array.

// where 'arr' is your original array
const new_arr = arr.map((item) => {

  // this is called a 'destructuring assignment'
  const [name, value] = item;

  // return the values as fields in an object
  return {name, value};

});
0
const arrArr = [['Reference', 'Price'], ['232323DD, 15.00]];
const objArr = [];

for (const item of arrArr) {
    objArr.push({name: item[0], value: item[1]});
}
pfeileon
  • 290
  • 1
  • 17
0

let arr = [
  ['Reference', 'Price'],
  ['232323DD', '15.00']
];
    
let result = arr[0].map((key, i) => ({name: key, value: arr[1] ? arr[1][i] : null}));
console.log(result);
MarcoS
  • 17,323
  • 24
  • 96
  • 174
0

I'll try to break this down:

// 1. create a new arr object:
let convertedArr = [];

// 2. loop over the original array:
for(let i = 0; i < arr.length; i++){

let currentItem = arr[i];

//create a temp object
let obj = {name:currentItem[0], value: name:currentItem[1] };

//push a new object to the array
convertedArr.push(obj);

}
calios
  • 525
  • 5
  • 13