简体   繁体   English

从数组映射返回对象

[英]return object from array map

Suppose I could hardcode the following:假设我可以硬编码以下内容:

const data = [ { a: 0, b: 1}, {a:2,b:3},... ]

But I have the data in an array, and I would like to write something like the following:但是我有一个数组中的数据,我想写如下内容:

const data = my_arr.map((element,index) => { a:element, b:index});

How does one yield this kind of object from an array map?如何从数组映射中产生这种对象?

You just need to add parenthesis around the returned object literal.您只需要在返回的对象文字周围添加括号。

 const my_arr = [1,2,3,4,5]; const data = my_arr.map((element, index) => ({ a: element, b:index })); // ^ ^ console.log(data);

The reason is that the JavaScript parser rules assume that the { following the => is the start of a function body.原因是 JavaScript 解析器规则假定=>后面的{是函数体的开始。 To go around this, we wrap the object in () (alternatively we can add a return statement)为了解决这个问题,我们将对象包装在() (或者我们可以添加一个return语句)

Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Returning_object_literals在此处阅读更多信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Returning_object_literals

Ah, figured this out.啊,想通了。

The anonymous object clashes with the scope operators, so you need to encapsulate the object in a scope block, and pass the object by return from there:匿名对象与作用域运算符发生冲突,因此您需要将对象封装在作用域块中,并通过从那里返回来传递对象:

const data = my_arr.map((element,index) => { return {a:element,b:index}});

You have to add parenthesis around your returned object to differentiate it from a simple block:您必须在返回的对象周围添加括号以将其与简单块区分开来:

 const my_arr = [1, 2, 4, 3, 4]; const data = my_arr.map((element, index) => ({ a: element, b: index })); console.log(data);

Or return it explicitly :或者明确返回:

 const my_arr = [1, 2, 4, 3, 4]; const data = my_arr.map((element, index) => { return { a: element, b: index }; }); console.log(data);

I guess it's the same我想是一样的

 var my_arr = [...Array(5).keys()] var result = my_arr.map((element,index) => ({ a: element, b: element + 1 })); console.log('result', result)

So, it works所以,它有效

See output:见输出:

 var results = []; [...Array(11).keys()].forEach((el) => { if (el % 2 === 0) { results.push({ a: el, b: el + 1 }) } }) console.log('results',results)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM