admin管理员组文章数量:1208155
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?
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?
Share Improve this question asked Feb 12, 2019 at 22:16 ChrisChris 31.2k31 gold badges100 silver badges187 bronze badges 05 Answers
Reset to default 18You 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. To go around this, we wrap the object in ()
(alternatively we can add a return
statement)
Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Returning_object_literals
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);
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}});
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)
本文标签: javascriptreturn object from array mapStack Overflow
版权声明:本文标题:javascript - return object from array map - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738707050a2107976.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论