0

I am having this format in my script

//declaration of JSON object
items= {};
items.values= [];

I need a structure like this, which is inserted automatically when the script is executed:

    items : 
        {
        key :['one', 'two', 'three', 'four'],
        values: [1, 2, 3, 4]
        }

Since the item.values[0] is undefined, it throws me a undefined error. Can anyone please tell me how to initialize the JSON object, such that it wont throw undefined error

I would like to insert like this:

var i=0;
item.key[i]= 'one';
item.values[i]= 1;

I am not sure whether this is the best practice, if anyone knows better way please post it!

Thanks in advance

3
  • You define the object items and then you try to access the object item Commented Sep 28, 2015 at 15:54
  • Please show more code... items.values is already an array but items.key is undefined and it seems like you have something backwards in the question. Also this is not a json object ... there is no such thing since json is string data Commented Sep 28, 2015 at 15:56
  • Sorry about that, items.key =[] is also defined. I need to do like this, var i=0; item.key[i]= 'one'; item.values[i]= 1; Commented Sep 28, 2015 at 16:00

1 Answer 1

2

You have the right idea. It looks like your property for adding keys isn't there though. Let's declare two properties, keys and values.

items= {};
items.keys = [];
items.values= [];

Our JavaScript object now looks like this

{ "keys": [], "values": [] }

var words = ['one', 'two', 'three', 'four'];
var numbers = [1,2,3,4];

You now want to iterate using a forloop. In JavaScript, arrays are 0-indexed, meaning the first element has an index of 0. That's why we initialize the i variable with a value of 0. After every iteration, we increment this variable and then check if it's less than the length of the array.

function populateObject() {
    for (var i = 0; i < words.length; i++) {
        items.keys.push(words[i]);
        items.values.push(numbers[i]);
    }
}

And then call your function

populateObject();

Here is the output

{"keys": ["one", "two", "three", "four"], "values": [1, 2, 3, 4]}
Sign up to request clarification or add additional context in comments.

1 Comment

I found a way for my problem. Anyway thanks for the answers and 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.