Get JavaScript object from array of objects by val

2018-12-31 03:23发布

This question already has an answer here:

Let's say I have an array of four objects:

var jsObjects = [
   {a: 1, b: 2}, 
   {a: 3, b: 4}, 
   {a: 5, b: 6}, 
   {a: 7, b: 8}
];

Is there a way that I can get the third object ({a: 5, b: 6}) by the value of the property b for example without a for...in loop?

17条回答
无色无味的生活
2楼-- · 2018-12-31 04:18

To get first object from array of objects by a specific property value:

function getObjectFromObjectsArrayByPropertyValue(objectsArray, propertyName, propertyValue) {
  return objectsArray.find(function (objectsArrayElement) {
    return objectsArrayElement[propertyName] == propertyValue;
  });
}

function findObject () {
  var arrayOfObjectsString = document.getElementById("arrayOfObjects").value,
      arrayOfObjects,
      propertyName = document.getElementById("propertyName").value,
      propertyValue = document.getElementById("propertyValue").value,
      preview = document.getElementById("preview"),
      searchingObject;
  
  arrayOfObjects = JSON.parse(arrayOfObjectsString);
  
  console.debug(arrayOfObjects);
  
  if(arrayOfObjects && propertyName && propertyValue) {
    searchingObject = getObjectFromObjectsArrayByPropertyValue(arrayOfObjects, propertyName, propertyValue);
    if(searchingObject) {
      preview.innerHTML = JSON.stringify(searchingObject, false, 2);
    } else {
      preview.innerHTML = "there is no object with property " + propertyName + " = " + propertyValue + " in your array of objects";
    }
  }
}
pre {
  padding: 5px;
  border-radius: 4px;
  background: #f3f2f2;
}

textarea, button {
  width: 100%
}
<fieldset>
  <legend>Input Data:</legend>
  <label>Put here your array of objects</label>
  <textarea rows="7" id="arrayOfObjects">
  [
    {"a": 1, "b": 2},
    {"a": 3, "b": 4},
    {"a": 5, "b": 6},
    {"a": 7, "b": 8, "c": 157}
  ]
  </textarea>

  <hr>

  <label>property name: </label> <input type="text" id="propertyName"  value="b"/>
  <label>property value: </label> <input type="text" id="propertyValue" value=6 />
     
</fieldset>
<hr>
<button onclick="findObject()">find object in array!</button>
<hr>
<fieldset>
  <legend>Searching Result:</legend>
  <pre id="preview">click find</pre>
</fieldset>

查看更多
看淡一切
3楼-- · 2018-12-31 04:20

Try Array filter method for filter the array of objects with property.

var jsObjects = [
   {a: 1, b: 2}, 
   {a: 3, b: 4}, 
   {a: 5, b: 6}, 
   {a: 7, b: 8}
];

using array filter method:

var filterObj = jsObjects.filter(function(e) {
  return e.b == 6;
});

using for in loop :

for (var i in jsObjects) {
  if (jsObjects[i].b == 6) {
    console.log(jsObjects[i]); // {a: 5, b: 6}
  }
}

Working fiddle : https://jsfiddle.net/uq9n9g77/

查看更多
还给你的自由
4楼-- · 2018-12-31 04:20

OK, there are few ways to do that, but let's start with the simplest one and latest approach to do this, this function is called find().

Just be careful when you using find to as even IE11 dosn't support it, so it needs to be transpiled...

so you have this object as you said:

var jsObjects = [
   {a: 1, b: 2}, 
   {a: 3, b: 4}, 
   {a: 5, b: 6}, 
   {a: 7, b: 8}
];

and you can write a function and get it like this:

function filterValue(obj, key, value) {
  return obj.find(function(v){ return v[key] === value});
}

and use the function like this:

filterValue(jsObjects, "b", 6); //{a: 5, b: 6}

Also in ES6 for even shortened version:

const filterValue = (obj, key, value)=> obj.find(v => v[key] === value);

This method only return the first value which match..., for better result and browser support, you can use filter:

const filterValue = (obj, key, value)=> obj.filter(v => v[key] === value);

and we will return [{a: 5, b: 6}]...

This method will return an array instead...

You simpley use for loop as well, create a function like this:

function filteredArray(arr, key, value) {
  const newArray = [];
  for(i=0, l=arr.length; i<l; i++) {
    if(arr[i][key] === value) {
      newArray.push(arr[i]);
    }
  }
 return newArray;
}

and call it like this:

filteredArray(jsObjects, "b", 6); //[{a: 5, b: 6}]
查看更多
牵手、夕阳
5楼-- · 2018-12-31 04:24

If I understand correctly, you want to find the object in the array whose b property is 6?

var found;
jsObjects.some(function (obj) {
  if (obj.b === 6) {
    found = obj;
    return true;
  }
});

Or if you were using underscore:

var found = _.select(jsObjects, function (obj) {
  return obj.b === 6;
});
查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 04:24
var jsObjects = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8}];

to access the third object, use: jsObjects[2];
to access the third object b value, use: jsObjects[2].b;

查看更多
登录 后发表回答