0

Being a beginner in Javascript and after failing with all the available solutions on this site, I am posting this question. I have a variable as given below:

var p = 
{
    "name": "Country",
    "entries": [{
        "value": "India",
        "synonyms": []
    },
    {
        "value": "USA",
        "synonyms": []
    }
   ]
};

If I have an array of hundred countries, how can I loop through entries of variable p and add hundred countries to it?

3
  • 1
    Post a sample of the content of your array of countries. Commented Sep 10, 2017 at 15:35
  • 4
    Why do you want to loop? p.entries.push(...moreCountries) would append all elements of moreCountries to p.entries. p only has two properties, so looping doesn't seem to me necessary? Either way, if you want help you should provide a complete example. That includes examples of the inputs and an example of the desired output. Also this is not JSON, it's an object literal. Commented Sep 10, 2017 at 15:37
  • When I say more specifically you can use the code as p.entries.push({"value" : i,"synonyms":array_variable}); Commented Sep 10, 2017 at 15:44

2 Answers 2

1

In ES6 you can use spread argument for this task:

//...
var arrayOfCountries = [
  {
     "value": "Germany",
     "synonyms": []
  },
  {
    "value": "Russia",
    "synonyms": []
  }
]; 

p.entries.push(...arrayOfCountries);

Or if you are using ES5 or older try concat method:

// ...
p.entries = p.entries.concat(arrayOfCountries);
Sign up to request clarification or add additional context in comments.

Comments

0

You can loop through p.entries

e.g.

for ( var i = 0 ; i < p.entries.length ; i++){
var value = p.entries[i].value;
var synonyms = p.entries[i].synonyms;

}

2 Comments

OP is asking to add an array of countries to the existing p object.
Yes, I am asking how to add things into the array

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.