简体   繁体   中英

Creating complex objects dynamically in javascript

Is it possible to create complex objects at runtime in javascript ? If so, what is the correct syntax ?

var food = {};
food["fruit"]["yellow"] = "banana";
food["meat"]["red"] = "steak";
food."fruit"."green" = "apple";

It's not clear what you're trying to do. If you want to build that object up all at once, then you could do something like:

var food = {
    fruit: {
        yellow: 'banana',
        green: 'apple'
    },
    meat: {
        red: 'steak'
    }
};

If you need to piece it together one nested object at a time, then you just need to make sure that you are creating a new object to add properties to.

For example, your line:

food["fruit"]["yellow"] = "banana";

will probably fail because food.fruit does not exist.

You should do:

var food = {};
food.fruit = {};
food.fruit.yellow = 'banana';

You could write a function to add data to your object. eg

function addEntry(obj, entry) {
  if(entry.length < 2) return;
  if(entry.length === 2) obj[entry[0]] = entry[1];
  else {
    if(!obj[entry[0]] || typeof obj[entry[0]] !== "object") obj[entry[0]] = {};
    addEntry(obj[entry[0]], entry.slice(1));
  }
}

var data = [
  ["fruit", "yellow", "banana"],
  ["meat", "red", "steak"],
  ["fruit", "green", "apple"]
];

var obj = {};
for(var i = 0; i < data.length; i++) {
  addEntry(obj, data[i]);
}

console.log(obj);

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