Agnaroc
Agnaroc

Reputation: 177

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";

Upvotes: 0

Views: 2700

Answers (2)

Tesseract
Tesseract

Reputation: 8139

You could write a function to add data to your object. e.g.

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);

Upvotes: 1

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107626

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';

Upvotes: 3

Related Questions