0

So I have a 2d array containing multiple objects. Each object has multiple properties and methods. I would like to return only the objects methods and properties that have a matching id to what I pass it. in this case, the id is 1.

const blogData = [
    {
        title : "Title 1",
        date : "2017-07-15",
        id : 1
    },
    {
        title : "Title 2",
        data : "2017-07-16",
        id : 2
    }
];

for (let i = 0; i < blogData.length; i++) {
  if (blogData[i].id === 1) {
      console.log(`Post #${blogData[i].id} loaded`);
  }                        
}
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Miles
  • 39
  • 1
  • 7

3 Answers3

2

You can filter the array based on ID, and assuming you just have one hit, you can return the first (and only) item, or skip shift() and get an array of matches.

const blogData = [{
    title: "Title 1",
    date: "2017-07-15",
    id: 1
  },
  {
    title: "Title 2",
    data: "2017-07-16",
    id: 2
  }
];

var result = blogData.filter( x => x.id === 1).shift();

console.log(result)
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

You can use a generic function that will work with any ID and any list.
Something like:

    const blogData = [
        {
            title : "Title 1",
            date : "2017-07-15",
            id : 1
        },
        {
            title : "Title 2",
            data : "2017-07-16",
            id : 2
        }
    ];
    
    function getData(id, arr, callback){
       $.each(arr, function(key, value){
         if(value.id === id)
           callback(value); //Just using a simple callback for console purposes
          });
    }
    
    $(document).ready(function(){
     getData(1, blogData, function(c){
        console.log(c); //loggin the callback
      });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
henrique romao
  • 560
  • 1
  • 8
  • 32
0

In your case this is an array of objects and not a 2 dimentional array, so you can use Array.prototype.filter() method to filter only the object that has the id=1:

var res = blogData.filter(function(obj){
  return obj.id === searchedId;
}).shift();

Demo:

const blogData = [
    {
        title : "Title 1",
        date : "2017-07-15",
        id : 1
    },
    {
        title : "Title 2",
        data : "2017-07-16",
        id : 2
    }
];

var searchedId = 1;

var res = blogData.filter(function(obj){
  return obj.id === searchedId;
}).shift();
console.log(res);

And using your method with foor loop, you just need to return the right object if the condition is matched:

var result = {};
for (let i = 0; i < blogData.length; i++) {
  if (blogData[i].id === 1) {
      result = blogData[i]
  }                        
}
cнŝdk
  • 31,391
  • 7
  • 56
  • 78