简体   繁体   中英

nesting object within another array

i have an array and an object.

var myObj = { "abc": 200, "xyz": 300};
vay myArray = ["one", "two"]

i want to next the values of myObj inside "one".

so myArray[0] would return object data-

the console.log(myArray) would look something like.

-"one"
    *Object
            *abc:200
            *xyz:300
-"two"

i tried using push to add myObj to myArray[0], but it did not work. Any suggestions.

Update:
My code looks like this now, maybe this will help me ask correctly:

var allData = {
user1:[userData]}

this runs each time a function is called.

userData the first time is ex: {name:bob, id:123} and {name:dave, id:456} the second time the function runs.

but if i do a console.log{allData) , i only see the last userDat objecta. i would like it to add on to the user1 each time i use the function so that i could essentially do the following allData.user1[1].name; and get "dave"

The following structure is what you seem to be asking for:

var myArray = [
                { "one" : { "abc": 200, "xyz": 300} },
                "two"
              ];

That is, the first element in the array becomes an object that has one property named "one", and the property references the object { "abc": 200, "xyz": 300} . The second element in the array is still just a string, "two".

To access the "abc" property you'd say myArray[0]["one"]["abc"] or myArray[0].one.abc . This seems kind of clunky and perhaps isn't at all what you want, but as I said it's what you seem to be asking for.

If the object and array both already exist as shown in your question and you want to use the current value of array element 0 to be the key in the object you can do this:

var myObj = { "abc": 200, "xyz": 300},
    myArray = ["one", "two"];

var tempObj = {};
tempObj[myArray[0]] = myObj;
myArray[0] = tempObj;

It seems to me that a more sensible structure would be:

var myObj = {
       "one" : { "abc": 200, "xyz": 300 },
       "two" : null
};

So that you can simply say myObj["one"]["abc"] or myObj.one.abc .

I assume you want it a generic approach(not with any hardcoded values), in which case try this:

    var myObj = { "abc": 200, "xyz": 300}; 
    var myArray = ["one", "two"];
    var one = myArray[0];
    var temp = {};
    temp[one] = myObj;
    myArray[0] = temp;
    console.log(myArray);

[{“ abc”:200,“ xyz”:300},“两个”]或[{“ one”:{“ abc”:200,“ xyz”:300}},“两个”] your myArray [0]是一个String,没有push方法

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