1

I have an array as such:

 data = [
    {id:343, article:'yes', image:'ok'},
    {id:35, article:'ko', image:'twe'},
    {id:212, article:'ere', image:'efe'},
    {id:90, article:'fefe', image:'fe'}
    ]

I am trying to loop through the array object, then grab id, article, and image data where id is equal to a certain number. So for example I want to grab id, article, and image when id is equal to 90.

I am able to discern the array and if the id exists as such:

data.forEach(function(key,value){
            if (key['id'] === 343) {
                //how to grab rest of this object?
            }
        })

but from there I don't know how to grab the rest of the object data.

How would I go about this? Any help would be greatly appreciated.

NullPointer
  • 7,094
  • 5
  • 27
  • 41
Zach Smith
  • 5,490
  • 26
  • 84
  • 139

2 Answers2

1
  1. You are almost there.Get the value from object based on key

data = [
    {id:343, article:'yes', image:'ok'},
    {id:35, article:'ko', image:'twe'},
    {id:212, article:'ere', image:'efe'},
    {id:90, article:'fefe', image:'fe'}
    ]

var result={}
data.forEach(function(item){
    if (item['id'] === 343) {
    result=item;
    }
});
console.log(result.id,result.article,result.image);
  1. You can also use Array.propotype.filter() or Array.prototype.find()

data = [
{id:343, article:'yes', image:'ok'},
{id:35, article:'ko', image:'twe'},
{id:212, article:'ere', image:'efe'},
{id:90, article:'fefe', image:'fe'}
]

var result = data.filter(obj => obj.id == 343);
console.log(result);


result= data.find(obj => obj.id === 343);
console.log(result.id,result.article,result.image);
NullPointer
  • 7,094
  • 5
  • 27
  • 41
  • i like it. is this quicker than looping through one by one compared to my `forEach`? suppose i have 10000 entries in my array i have to loop through... – Zach Smith Sep 23 '18 at 02:15
  • Always **for loop** are more proficient than **for each** than **map/reduce/filter/find**. In case of if you have multiple items then it will be better to do the filter based on condition – NullPointer Sep 23 '18 at 02:21
0

Use Array.find:

const item = data.find(o => o.id === 343);
Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66