简体   繁体   中英

How to access an object inside an Array Javascript

I have a bunch of objects in an Array.

  • How can I access the objects?
  • And how to add a key to every object?

Example

var gradesArr = [
    {
        'name' : 'Пешо',
        'score' : 91
    },
    {
        'name' : 'Лилия',
        'score' : 290
    },
    {
        'name' : 'Алекс',
        'score' : 343,
    },
    {
        'name' : 'Габриела',
        'score' : 400
    },
    {
        'name' : 'Жичка',
        'score' : 70
    }]

I want to add a key hasPassed to the objects, which have a score over 100.

But I can't mind of a way to do this.

You can loop through the Array and add a property to those objects. Eg:

for (var i = 0; i < gradesArr.length; i++) {
  if (gradesArr[i].score > 100) {
    gradesArr[i].hasPassed = true;
  }
}

 var gradesArr = [{ 'name': 'Пешо', 'score': 91 }, { 'name': 'Лилия', 'score': 290 }, { 'name': 'Алекс', 'score': 343, }, { 'name': 'Габриела', 'score': 400 }, { 'name': 'Жичка', 'score': 70 }]; for (var i = 0; i < gradesArr.length; i++) { if (gradesArr[i].score > 100) { gradesArr[i].hasPassed = true; } } document.querySelector('pre').innerHTML = JSON.stringify(gradesArr, null, 2); 
 <pre></pre> 

You can use the forEach method of arrays to apply the desired changes.

 var gradesArr = [{ 'name': 'Пешо', 'score': 91 }, { 'name': 'Лилия', 'score': 290 }, { 'name': 'Алекс', 'score': 343, }, { 'name': 'Габриела', 'score': 400 }, { 'name': 'Жичка', 'score': 70 }]; gradesArr.forEach(function(person) { if (person.score > 100) { person.hasPassed = true; } }); document.getElementById("my_out").innerHTML = JSON.stringify(gradesArr); 
 <div id="my_out"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM