首页 > 解决方案 > find the length of array using map function ES6

问题描述

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)

标签: javascriptecmascript-6

解决方案


使用 ES6,要从变量创建对象的键,您必须使用[].

例如:

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

console.log(name);

所以这就是你要找的:

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


推荐阅读