0

So my goal is to have an object variable that will be empty at the start but as the code starts running it would get filled up with data from other varibales. When it gets filled up it should look like this:

var fruits = [banana, apple, ...];
var colors = [yellow, green, ...];
var calories = [300, 250, ...]

//the JSON object
{
    banana : 
    {
        "color" : "yellow",
        "calories" : 300
    },
    apple :
    {
        "color" : "green",
        "calories" : 250
    },
    ...
}

As you can see all of the data is supposed to be pulled from other variables and this is where I bump into problems. I've tried the following:

var object.fruits[0] = {colors : calories};

//also tried this
var object.fruits[0] = "{""'" + (colors[0]) + "'":+calories[0]+"}";
//and tried many other things...

I've been failing to counter this for at least an hour now and what makes it worse is that some data is supposed to come from other JSON objects. Any idea how to make it work? Also note that having them in an object array is not a option as the list will be HUGE and therefore the time efficiency will be very poor.

3 Answers 3

1

Maybe try something like this

res = {}

fruits.map((key, index) => {
    res[key] = {
        'color': colors[index],
        'calories': calories[index]
    }
})
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah that works, but what if I have to pull the fruits name from another JSON object?
Use Object.keys() to subtract all keys in the JSON object and use them to find the corresponding fruit name in your JSON object. Basically, it works like a HashMap/Dictionary.
1

You can do like this but yeah put validations to make sure all three arrays are of equal length.

Whenever you want to add a property to an Object where the property value is a value of another variable it is better to use the bracket notation to add the properties to the object [] as used below.

One more thing better use let and const in place of var.

Finally you can use JSON.stringify() to convert into JSON String from the Javascript Object.

'use strict';

const fruits = ['banana', 'apple'];
const colors = ['yellow', 'green'];
const calories = [300, 250];

const fruits_object = {};
for (let i = 0; i < fruits.length; i++) {
  fruits_object[fruits[i]] = {};
  fruits_object[fruits[i]]['color'] = colors[i];
  fruits_object[fruits[i]]['calories'] = calories[i];
}

console.log(JSON.stringify(fruits_object));

Comments

0

Just do it normally like so:

color: colors[0]

and then call JSON.stringify on the entire object like so

JSON.stringify({color: colors[0]})

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.