Allison
Allison

Reputation: 65

Find if a JSON Value contains certain text

I'm not sure if this is possible, because I have not found anything on this.. I am going through a JSON object..

{"name": "zack",
 "message": "hello",
 "time": "US 15:00:00"},

{"name": "zack",
 "message": "hello",
 "time": "US 00:00:00"}

Is there a way I can select the time property that contains just the "15:00:00" part?

Thanks for the help

Upvotes: 3

Views: 6805

Answers (4)

Vivek N
Vivek N

Reputation: 304

var arr = [{
    "name": "zack",
    "message": "hello",
    "time": "US 15:00:00"
}, {
    "name": "zack",
    "message": "hello",
    "time": "US 00:00:00"
}]

for (var i = 0; i < arr.length; i++) {
    var time = (arr[i].time.split('US '))[1];
    console.log(time);
}

Upvotes: 1

Sachin Gupta
Sachin Gupta

Reputation: 8378

You can use filter function to filter the array, and can use indexOf to check whether time field contains 15:00:00 or not.

E.g:

var json = [{
    "name": "zack",
    "message": "hello",
    "time": "US 15:00:00"
  },

  {
    "name": "zack",
    "message": "hello",
    "time": "US 00:00:00"
  }
];


 var resultObj = json.filter(item=>item.time.indexOf("15:00:00") !== -1);
 console.log(resultObj);

Upvotes: 1

brk
brk

Reputation: 50291

You can use array#filter function. It will return a new array with matched element. If the length of new array is 0 then no match was found

var myJson = [{
    "name": "zack",
    "message": "hello",
    "time": "US 15:00:00"
  },

  {
    "name": "zack",
    "message": "hello",
    "time": "US 00:00:00"
  }
]

var m = myJson.filter(function(item) {
  return item.time === "US 15:00:00"

})

console.log(m)

findIndex can also be used to find if it contains the value. If the value is -1 it mean the json array does not contain any object that match the criteria

var myJson = [{
    "name": "zack",
    "message": "hello",
    "time": "US 15:00:00"
  },

  {
    "name": "zack",
    "message": "hello",
    "time": "US 00:00:00"
  }
]

var m = myJson.findIndex(function(item) {
  return item.time === "US 15:00:00"

});
console.log(m)

Upvotes: 0

Christos
Christos

Reputation: 53958

As I understand if you parse your JSON you have an array of object. So you can make use of filter function and filter out those elements that don't match the criteria you pass in filter function:

var parsedJson = [{"name": "zack",
 "message": "hello",
 "time": "US 15:00:00"},{"name": "zack",
 "message": "hello",
 "time": "US 00:00:00"}];
 
 var result = parsedJson.filter(item=>item.time === "US 15:00:00");
 
 console.log(result);
 

Upvotes: 1

Related Questions