quo91
quo91

Reputation: 139

Adding data to JSON object with data from variables

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.

Upvotes: 0

Views: 656

Answers (3)

Vamsi
Vamsi

Reputation: 35

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

Upvotes: 1

yli
yli

Reputation: 26

Maybe try something like this

res = {}

fruits.map((key, index) => {
    res[key] = {
        'color': colors[index],
        'calories': calories[index]
    }
})

Upvotes: 1

Vikram Khemlani
Vikram Khemlani

Reputation: 635

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]})

Upvotes: 0

Related Questions