0

I have this structure:

materials= ["a","b","c"]

and I need it to be like this:

data= [{material:"a"},{material:"b"},{material:"c"}]
asked Feb 6, 2020 at 12:32
5
  • 1
    Okay, good luck. be sure to let us know if you have any questions. Commented Feb 6, 2020 at 12:33
  • 1
    what have you done so far? Commented Feb 6, 2020 at 12:33
  • 2
    Welcome to SO. What did you try ? You should try to solve the problem yourself and post question showing how you attempted it and maybe point out what's not working to get an answer which will solve your problem and clear your understanding. (Win/Win :) Happy coding. Commented Feb 6, 2020 at 12:34
  • use array map for this developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Feb 6, 2020 at 12:34
  • materials.map(material => ({material})) Commented Feb 6, 2020 at 12:38

6 Answers 6

3

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)

answered Feb 6, 2020 at 12:34
Sign up to request clarification or add additional context in comments.

2 Comments

const result = materials.map(material => ({material}));
Thank you very much, I was trying to do it with Array.forEach() but I was sure there was a cleaner method, now I finally understand what .map() does!
3

You could use map method.

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

answered Feb 6, 2020 at 12:34

Comments

0

You can use Array.forEach():

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

answered Feb 6, 2020 at 12:33

Comments

0
const obj = materials.map((material)=>{
 return ({"material": material})
 });
console.log(obj);
answered Feb 6, 2020 at 12:34

Comments

0

I would use Array.map:

const test = ["a", "b", "c"];
const result = test.map(e => {
 return { material: e };
});
console.log(test);
console.log(result);

answered Feb 6, 2020 at 12:37

Comments

0
let materials= ["a","b","c"]
let newObj = materials.map(material => ({material}));
console.log(newObj);
answered Feb 6, 2020 at 12:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.