0

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";
3
  • var food = {}; food["fruit"] = {}; food["fruit"]["yellow"] = "banana"; food["meat"] = {}; food["meat"]["red"] = "steak"; food["fruit"]["green"] = "apple"; Commented Mar 18, 2016 at 18:33
  • My problem is this needs to happen dynamically, if I get food["meat"] 2 times I can't use food["meat"] = {} because the previous food->meat entry would be lost Commented Mar 18, 2016 at 18:35
  • Could you describe what you're trying to do in more detail? To me, this question is very unclear. Commented Mar 18, 2016 at 18:36

2 Answers 2

3

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';
Sign up to request clarification or add additional context in comments.

1 Comment

I'm iterating through data in a file.I don't know if food is going to come along at all. So if there isn't any way around it I'll always use if(data.fruit == undefined) {var fruit = {}; } //Do something with data.fruit
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.