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.

Share Improve this question asked Feb 9, 2020 at 18:45 baal_imagobaal_imago 3134 silver badges11 bronze badges 3
  • 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
Add a ment  | 

3 Answers 3

Reset to default 6

You 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