4

How to create an array of objects that has two properties name and shade?

[{
    "name": "black",
    "shade": "dark"
  }, {
    "name": "white",
    "shade": "light"
  },
  {
    "name": "red",
    "shade": "dark"
  }, {
    "name": "blue",
    "shade": "dark"
  },
  {
    "name": "yellow",
    "shade": "light"
  }
]

I have two different arrays now.

name = ["black","white","red","blue","yellow"]
shade = ["dark","light","dark","dark","light"]

How can I achieve this?

1
  • I was actually looking for the opposite of this .ie. I have an array of objects and want to split the 2 properties into 2 different arrays. Any idea please ? Commented Sep 6, 2019 at 9:52

4 Answers 4

6

Use map

var output = name.map( (s, i) => ({name : s, shade : shade[i]}) );

Demo

var name1 = ["black","white","red","blue","yellow"];

var shade = ["dark","light","dark","dark","light"];

var output = name1.map( (s, i) => ({name : s, shade : shade[i]}) );

console.log( output );

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you.....if array is if different size and if i want to map first element of property to third element of shade property how would u do that
1
var new_array = [];
// assuming the arrays have the same length
for (var i = 0; i < name.length; i++)
    new_array.push({name: name[i], shade: shade[i]});

Comments

1

You can use .map():

let names = ["black", "white", "red", "blue", "yellow"],
    shades = ["dark", "light", "dark", "dark", "light"];

let merge = (a1, a2) => names.map((n, i) => ({name: n, shade: shades[i]}));

console.log(merge(names, shades));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

1

You could take a helper object for addressing the types.

var names = [ "black", "white", "red", "blue", "yellow"],
    shades = ["dark", "light", "dark", "dark", "light"],
    temp = { name: names, shade: shades },
    result = Object
        .keys(temp)
        .reduce(
            (r, k) => (temp[k].forEach((v, i) => (r[i] = r[i] || {})[k] = v), r),
            []
        );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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.