0

I want to combine two arrays into one Object with name "data" Didn't find any efficient way

arrays:

var N =[ 1, 2, 3];
var s =[ a, b, c];

combine them into object:

var data= { s:[ a, b, c], N: [ 1, 2, 3 ] };
2
  • 5
    var data = {s: s, N: N};! Or in recent ECMAScripts: var data = {s, N};! Commented Mar 15, 2017 at 17:39
  • var data = { s, N }; (ES6) Commented Mar 15, 2017 at 17:39

4 Answers 4

2

The easiest way would be:

const N = [1, 2, 3];
const s = ['a', 'b', 'c'];
const data = { s, N };

This is equivalent to:

const N =[ 1, 2, 3];
const s = ['a', 'b', 'c'];
const data = { s: s, N: N };

Note: I used const since the variables aren't reassigned.

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

Comments

1

Do it this way:

var N =[ 1, 2, 3];
var s =[ a, b, c];

var obj = {N, s};

Comments

1

var N =[ 1, 2, 3];
var s =[ 'a', 'b', 'c'];

var data = {s, N};
console.log(data);

Comments

0

Just pass your arrays (N and s) as variables to your new object. You can do this in few ways:

  1. let myObject = { N: N, s: s } If you do this way you can type any other key. For example: let myObject = { firstArray: N, secondArray: s } and now you can access to N and s arrays as myObject.firstArray etc

  2. Use short notation: let myObject = { N, s } This code will look up for variables N and s and write it inside your new object, which will give the same result as let myObject = { N: N, s: s }

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.