简体   繁体   中英

How can I create a nested array in JavaScript?

With the code below:

var result = [];
result.push({success : 1});
for (var i = 0; i < rows.length; i++) {
    result.push({email : rows[i].email});
};

I create an array that looks like this:

[
  {
    "success": 1
  },
  {
    "email": "email1@email.com"
  },
  {
    "email": "email2@email.com"
  },
  {
    "email": "emailN@email.com"
  }
]

But I want to create an array that looks like this:

[
  {
    "success": 1
  },
  {
    "email": ["email1@email.com","email2@email.com","emailN@email.com"]
  }
]

I'm stuck on the exact syntax for doing this. How can I put an array inside another array?

The email property in the result contains an Array , so create one for it.

var result = [];
var emails = [];

for (var i = 0; i < rows.length; i++) {
   emails.push(rows[i].email);
};

result.push({success : 1});
result.push({email: emails});
var result = [
  { success : 1 },
  { email   : rows.map(function(row) {
      return row.email;
    })
  }
];

Some explanation: rows is an array, and arrays in JS have a method .map() which can be used to process each item in the array and return a new array with the processed values.

For each item, a function is called with the value of the item, and whichever value is returned from that function is added to the new array.

In this case, the function returns the email property for each of the items, so you end up with an array of e-mail addresses, which is basically what you want.

EDIT : my initial suggestion was to make result an object instead:

var result = {
  success : 1,
  email   : rows.map(function(row) {
    return row.email;
  })
};

Whether this is better depends on the requirements for the structure of the data.

Simply create an array in the result object with the property email and then push the emails into it. See below.

var result = [];
result.push({success : 1});
var emails = []
for (var i = 0; i < rows.length; i++) {
    emails.push(rows[i].email);
};
result.push({email: emails})
var finalResult = [];    
finalResult.push({success : 1});
var result = [];
for (var i = 0; i < rows.length; i++) {
    result.push(email : rows[i].email);
};

finalResult.push({"email" : result});

i think above code will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM