Reputation: 171
I have this structure:
materials= ["a","b","c"]
and I need it to be like this:
data= [{material:"a"},{material:"b"},{material:"c"}]
Upvotes: 0
Views: 88
Reputation: 38199
You can use map
:
materials.map(a=> ({material: a}))
An example:
let materials= ["a","b","c"];
const result = materials.map(a=> ({material: a}))
console.log(result)
or even shorter (thanks to Ele):
materials.map(material => ({material}));
let materials= ["a","b","c"];
const result = materials.map(material => ({material}));
console.log(result)
Upvotes: 3
Reputation: 13
let materials= ["a","b","c"]
let newObj = materials.map(material => ({material}));
console.log(newObj);
Upvotes: 0
Reputation: 48437
You could use map
method.
var materials= ["a","b","c"]
console.log(materials.map(material => ({material})));
Upvotes: 3
Reputation: 2300
I would use Array.map:
const test = ["a", "b", "c"];
const result = test.map(e => {
return { material: e };
});
console.log(test);
console.log(result);
Upvotes: 0
Reputation: 901
const obj = materials.map((material)=>{
return ({"material": material})
});
console.log(obj);
Upvotes: 0
Reputation: 30739
You can use Array.forEach()
:
var materials= ["a","b","c"]
var res = [];
materials.forEach((a) => res.push({material: a}));
console.log(res);
Upvotes: 0