1

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.

3
  • Array.prototype.map will always return an array. 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. 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 Commented Apr 21, 2023 at 7:19

3 Answers 3

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
    };
});
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.