2

I have the following dataset

data=[{name: "hk", age:21, gender:"M"}, {name: "kk", age:31, gender:"M"},{name: "tk", age:11, gender:"F"}]

How could I test whether or not there is a person name "hk" and index of the found object.

I have checked with the following code, but it does not work.

data.hasOwnProperty("hk")
0

2 Answers 2

5

You'd have to iterate through the array and check each object for that

function hasName(prop, value, data) {
    return data.some(function(obj) {
        return prop in obj && obj[prop] === value;
    });
}

FIDDLE


EDIT:

if you want to return the index instead, one has to use a loop that keeps track of the index, something like forEach instead

function hasName(prop, value, data) {
    var result = -1;
    data.forEach(function(obj, index) {
        if (prop in obj && obj[prop] === value) {
            result = index;
            return false;
        }
    });
    return result;
}

FIDDLE

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks adeneo, it works and quite easy to use. I will mark as an answer when SOF allows me.
How could I get index of the found object ?
5

Try (like indexOf):

var data=[{name: "hk", age:21, gender:"M"}, {name: "kk", age:31, gender:"M"},{name: "tk", age:11, gender:"F"}]

function exists(name){
    var item, i = 0;
    while(item = data[i++])
        if(item.name == name) return --i
    return -1
}

alert("Exists tk? - Index: " + exists("tk")); //-1: not exists

6 Comments

Is there any built in method in javascript? rather than using while condition?
Yes, you can use some in a array, I used a loop since some still not supported in some browsers. It is even faster
How could I get index of the found object ?
Updated return index: To check if not exists, the value returns -1. Equivale to indexOf
Btw, I found that a regular for (var i = 0, n = data.length; i != n; ++i) operates faster than evaluating the array element each time.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.