Daggle
Daggle

Reputation: 171

Convert Array of String into Array of Objects

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

Answers (6)

StepUp
StepUp

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

Arun Kumar
Arun Kumar

Reputation: 13

let materials= ["a","b","c"]
let newObj = materials.map(material => ({material}));
console.log(newObj);

Upvotes: 0

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48437

You could use map method.

var materials= ["a","b","c"]
console.log(materials.map(material => ({material})));

Upvotes: 3

KieranLewin
KieranLewin

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

PrakashT
PrakashT

Reputation: 901

const obj = materials.map((material)=>{
               return ({"material": material})
             });

console.log(obj);

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

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

Related Questions