-2

I'm trying to find the length of an array using ES6 using the below code but it does not work.

a=[[1,2,3,4],[4,5,6]]
result = a.map(d=>({d[0]:d.length}))
console.log(result)

This works:-

a=[[1,2,3,4],[4,5,6]]
result = a.map(d=>({name:d[0], length:d.length}))
console.log(result)
user1050619
  • 19,822
  • 85
  • 237
  • 413

2 Answers2

0

I think you're looking for something like this if you're trying to end up with an array of objects with the first element of the original array as the property name and the length of the array as the property value:

a=[[1,2,3,4],[4,5,6]]
result = a.map(d=>({[d[0]]:d.length}))
console.log(result)
0

Using ES6, to create a key for an object from a variable, you have to wrap with [].

For example:

const a = 'first name';
const name = {
  [a]: 'john',
};

console.log(name);

So this is what you are looking for:

a=[[1,2,3,4],[4,5,6]]
result = a.map(d=>({[d[0]]:d.length}))
console.log(result)
Loc Mai
  • 217
  • 3
  • 9