I have a list of values
let values = ["value-01", "value-02"]
I go ahead and turn them into the list of objects:
let result = [];
for (let each of values) {
result.push({ value: each });
};
console.log(result)
which logs
[ { value: 'value-01' }, { value: 'value-02' } ]
I wonder if there is a shorter way to achieve this? In Python I could do it in a single line like so:
result = [{"value": each} for each in values]
I have a list of values
let values = ["value-01", "value-02"]
I go ahead and turn them into the list of objects:
let result = [];
for (let each of values) {
result.push({ value: each });
};
console.log(result)
which logs
[ { value: 'value-01' }, { value: 'value-02' } ]
I wonder if there is a shorter way to achieve this? In Python I could do it in a single line like so:
result = [{"value": each} for each in values]
Share
Improve this question
asked Jul 14, 2021 at 3:54
alphanumericalphanumeric
19.4k74 gold badges277 silver badges421 bronze badges
2 Answers
Reset to default 6It's a pretty simple mapping.
let values = ["value-01", "value-02"];
const result = values.map(value => ({ value }));
console.log(result);
While there is nothing wrong with using a for loop, you could make use of this code using map()
, split()
and puted property names:
let values = ["value-01", "value-02"];
let ans = values.map((a) => ({ [a.split('-')[0]] : a }))
console.log(ans);