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.

1
  • the two answers.@B001ᛦ Commented Sep 12, 2018 at 12:42

7 Answers 7

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; }

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

Comments

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.

Comments

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)

Comments

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};

});

Comments

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

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

Comments

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);

Comments

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);

}

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.