admin管理员组文章数量:1333636
I wish to do this:
const ret = [];
nums.forEach(num => {
const dict = [];
dict[num] = Math.random() * 2 - 1;
ret.push(dict);
});
where nums = ["const_0", "const_1"]
=> ret = [{const_0: random_number}, {const_1: random_number}]
.
I want to do this using the map function, for no better reason other than practice using map functions. Here's my current attempt:
let ret = [];
ret = nums.map( x => new Object()[x] = Math.random() * 2 - 1);
but this returns ret = [random_number, random_number]
, it fails to create the dictionary/Object.
I wish to do this:
const ret = [];
nums.forEach(num => {
const dict = [];
dict[num] = Math.random() * 2 - 1;
ret.push(dict);
});
where nums = ["const_0", "const_1"]
=> ret = [{const_0: random_number}, {const_1: random_number}]
.
I want to do this using the map function, for no better reason other than practice using map functions. Here's my current attempt:
let ret = [];
ret = nums.map( x => new Object()[x] = Math.random() * 2 - 1);
but this returns ret = [random_number, random_number]
, it fails to create the dictionary/Object.
- Array.prototype.map will always return an array. – Dan Oswalt Commented Feb 9, 2020 at 18:52
- 1 If you want to return an object from an array function, you may be wanting Array.prototype.reduce, which can be used to build a single object via iterating over the array. – Dan Oswalt Commented Feb 9, 2020 at 18:54
- Was trying to figure out how to create a dictionary from an array and found out the way to do so is reduce, as Dan Oswalt mentioned – Jay Hu Commented Apr 21, 2023 at 7:19
3 Answers
Reset to default 6You can do something like this
const res = nums.map(x => ({[x]: Math.random() * 2 - 1}));
which is just a shorthand to
const res = nums.map(x => {
return {
[x]: Math.random() * 2 - 1
};
});
In this case I believe you need to assign the object to a variable and return the variable. new Object() runs the constructor method but I don't think it returns a value? Not sure. But this should work:
(x) => {
let holder = {} // or new Object()
holder[x] = calculation
return holder
}
(I know, it's not nearly as pretty as your one-liner)
Create a simple empty object literal and use bracket notation to assign each key.
const keys = ['key1', 'key2'];
const result = keys.map(key => {
let obj = {};
obj[key] = (Math.random() * 2) - 1;
return obj;
});
console.log(result);
本文标签: How can I create a dictionaryhashmap within a map function in javascriptStack Overflow
版权声明:本文标题:How can I create a dictionaryhashmap within a map function in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742358392a2459872.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论