开发者

Jquery object search

开发者 https://www.devze.com 2023-04-12 14:24 出处:网络
I have the following object and what I would lik开发者_如何学JAVAe achieve is to get the index of theme if the name has match with a variable.

I have the following object and what I would lik开发者_如何学JAVAe achieve is to get the index of theme if the name has match with a variable.

for example: I'm making a loop in the views and if my task (something1) variable has matches with the name element than to return the index of object.

By the given example I should have as result 0,

var views = [

    {
        name: "something1",
        type: something1,
        columns: something1
    },

    {
        name: "something2",
        type: something2,
        columns: something2
    },

    {
        name: "something3",
        type: something3,
        columns: something3
    }

];


var task = 'something1';

$.each(views, function(index, value) {

    if (value.name = task) {
        alert(index);
    }

}); 


You dont really need jQuery for this:

See: http://jsfiddle.net/enNya/2/

var views = [
    {
        name: "something1",
        type: "something1",
        columns: "something1"
    },
    {
        name: "something2",
        type: "something2",
        columns: "something2"
    }
];

var task = 'something2';

// Set a var and maintain scope
var i;

// Loop each element of the array
for (i = 0; i < views.length; i++) {
    // If the X = Y the stop looping
    if (views[i].name == task) {
        break;
    }
}

// Check if it was not found
i = i == views.length ? false : i;

// Log the result
console.log(i);


It's just a matter of syntax, as lgt said don't forget toseparate elements within your object with commas. Aslo the correct 'equal' operator is '=='. 'value.name=task' would be always true. It means can I affect the content of 'task' into 'value.name'.

Here is your valid js.

Note that in this example you'll get 2 alertbox.. ;)

var views=[

{
name:"something1",
type:'something1',
columns:'something1'
},

{
name:"something1",
type:'something1',
columns:'something1'
},

{
name:"something2",
type:'something2',
columns:'something2',
},

];


var task='something1';

$.each(views, function(index, value) { 

        if (value.name==task){

            alert(index);
        }
}); 


replace something1 variable for 0 and value.name == task (double =)

var views=[{
    name:"something1",
    type:0,
    columns:0
}, {
    name:"something1",
    type:0,
    columns:0
}, {
    name:"something2",
    type:0,
    columns:0
}];

var task='something1';
$.each(views, function(index, value) { 
    if (value.name==task){
        return index;
    }
}); 
0

精彩评论

暂无评论...
验证码 换一张
取 消