简体   繁体   中英

Search JSON Array for a String and Retrieve Object that Contains it as a Value

My JSON is below. It contains two Objects, each with a few key value pairs. How can I search through the entire JSON array and pull the object that contains a particular string as a value?

In this case, I need to pull the object with the coupon_code: COUPON1, so that I can then pull the ID of that Coupon.

In short, I just need to get the id of the Coupon with coupon_code: COUPON1

[Object, Object]

  0: Object
  coupon_code: "COUPON1"
  created_at: "2013-06-04T13:50:20Z"
  deal_program_id: 1
  id: 7
  updated_at: "2013-06-04T13:50:20Z"
  __proto__: Object

  1: Object
  coupon_code: "COUPON3"
  created_at: "2013-06-04T15:47:14Z"
  deal_program_id: 1
  id: 8
  updated_at: "2013-06-04T15:47:14Z"

Thanks :)

You just loop through the array and look. There are lots of ways to do that in JavaScript .

Eg:

var a = /*...your array...*/;
var index = 0;
var found;
var entry;
for (index = 0; index < a.length; ++index) {
    entry = a[index];
    if (entry.coupon_code == "COUPON1") {
        found = entry;
        break;
    }
}

Or using ES5's Array#some method (which is one that can be "shimmed" for browsers that don't yet have it, search for "es5 shim"):

var a = /*...your array...*/;
var found;
a.some(function(entry) {
    if (entry.coupon_code == "COUPON1") {
        found = entry;
        return true;
    }
});

Write a generic find function :

function find (arr, key, val) { // Find array element which has a key value of val 
  for (var ai, i = arr.length; i--;)
    if ((ai = arr[i]) && ai[key] == val)
      return ai;
  return null;
}

Call as follows :

find (arr, 'coupon_code', 'COUPON1')
var result = null;
Objects.forEach(function(obj, i){
    if(obj.cupon_code == 'COUPON1'){
        return result = obj;
    }
});
console.log(result);

This will loop through your Array and check the coupon_code for your specified value. If it found something, it will return it in result .

Note that Array.forEach is available since JavaScript 1.6. You might want to take a look at which browser are supporting it.

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