简体   繁体   中英

How to convert a bunch of arrays into a single object?

Here is what im doing:

onClick, grab details immediate subnodes and publish it on html. Status = DONE // This works well

NOW, I am using a bunch of arrays to get this done.

node.eachSubnode(function(node) {
                   title[title.length] = node.name; // This is what i want to modify
                   data[data.length] = node.data; // This is what i want to modify
                });

Here is how they look currently:

title = ['Coffee', 'Tea'];
data = ["Americans", "Britishers"]; // i use a loop to iterate through these arrays and append to html.

Here is what i want it to be:

var preference = {
title: 'Coffee',
data: 'Americans'
},
{
title: 'Tea',
data: 'Americans
}

I want to create this using the node.eachSubnode loop.

I'm not sure if I understood correctly, but I think this is what you want:

var preferences = [];

node.eachSubnode(function(node) {
    preferences.push({
        title: node.name,
        data: node.data.germ
    });
});

You cannot create an object that looks exactly like that, I think you need an array with objects. Assuming your node is an array with the length property, this method is the fastest .

var preference = new Array(node.length||0), i = 0;
node.eachSubnode(function(node) {
    preference[i++] = {
        title: node.name,
        data: node.data.germ
    };
});

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