1

I am from a classical OOO background and finding it difficult to understand the javascript object literal construction. I need a javascript variable containing an array of name value pairs. I should be able to push name, value pairs to the array through a function. SOmehow, I am finding it confusing to create such data structure. Could you please help me know the correct syntax for the same:

What I am looking for

var selectedItemArray = array of name, value pairs

and i should be able to

selectedItemArray.push(name, value);

and

selectedItemArray.get(index);



var tagArray = [];



for (var i in secondaryTagsArray) {
    tagArray.push({tagId:secondaryTagsArray[i].secondary_tag_id,
                   tagName:secondaryTagsArray[i].secondary_tag_name 
                   });
 }

1 Answer 1

1
  1. Key-Value pairs can be created with JavaScript Objects, with Object lietral, like this

    {key: value}
    
  2. Arrays can be created with Array literal ([]) or with Array constructor like this

    new Array(size);
    

You can use both of them, like this

var array = [];
array.push({key1: value1});

Since JavaScript arrays begin with index 0, you need to access the first element with index 0, second with 1 and so on.

console.log(array[0]);

will print the first key-value pair stored at index 0.

Sign up to request clarification or add additional context in comments.

6 Comments

should the key be unique? What if I have to have same name but different values for each array item?
@user883561 Can you show some sample input? I might be able to help you understand better
Whatever you have done with tagArray is correct only. How is secondaryTagsArray defined?
Thanks. I will go ahead with the same implementation.
@user883561 If secondaryTagsArray is really an array, then you must use a for loop to iterate it, like this for (var i = 0; i < secondaryTagsArray.length; i += 1) {
|

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.