在Javascript对象数组中查找值[duplicate]

时间:2023-01-21 21:28:27

This question already has an answer here:

这个问题已经有了答案:

I know similar questions have been asked before, but this one is a little different. I have an array of unnamed objects, which contain an array of named objects, and I need to get the object where "name" is "string 1". Here is an example array.

我知道以前也有人问过类似的问题,但这次有点不同。我有一个未命名对象数组,它包含一个命名对象数组,我需要获得“name”是“string 1”的对象。这是一个示例数组。

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

Update: I should have said this earlier, but once I find it, I want to replace it with an edited object.

更新:我之前应该说过,但是一旦找到,我想用一个编辑过的对象替换它。

20 个解决方案

#1


121  

You can loop over the array and test for that property:

您可以对数组进行循环,并对该属性进行测试:

function search(nameKey, myArray){
    for (var i=0; i < myArray.length; i++) {
        if (myArray[i].name === nameKey) {
            return myArray[i];
        }
    }
}

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

var resultObject = search("string 1", array);

#2


350  

Finding the array element:

let arr = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

let obj = arr.find(o => o.name === 'string 1');

console.log(obj);


Replacing the array element:

let arr = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

let obj = arr.find((o, i) => {
    if (o.name === 'string 1') {
        arr[i] = { name: 'new string', value: 'this', other: 'that' };
        return true; // stop searching
    }
});

console.log(arr);

#3


88  

In ES6 you can use Array.prototype.find(predicate, thisArg?) like so:

在ES6中,可以使用Array.prototype。找到(谓词,thisArg ?)一样:

array.find(x => x.name === 'string 1')

http://exploringjs.com/es6/ch_arrays.html#_searching-for-array-elements https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

http://exploringjs.com/es6/ch_arrays.html _searching-for-array-elements https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

To then replace said object (and use another cool ES6 method fill) you could do something like:

然后替换上述对象(并使用另一种很酷的ES6方法填充),您可以执行以下操作:

let obj = array.find(x => x.name === 'string 1');
let index = array.indexOf(obj);
array.fill(obj.name='some new string', index, index++);

#4


20  

with underscore.js use the findWhere method:

与强调。js使用findWhere方法:

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];


var result = _.findWhere(array, {name: 'string 1'});

console.log(result.name);

See this in JSFIDDLE

看到这在JSFIDDLE

#5


16  

As per ECMAScript 6, you can use the findIndex function.

根据ECMAScript 6,您可以使用findIndex函数。

array[array.findIndex(x => x.name == 'string 1')]

#6


11  

Either use a simple for-loop:

或者使用简单的for-loop:

var result = null;
for (var i = 0; i < array.length; i++) { 
  if (array[i].name === "string 1") { 
    result = array[i];
    break;
  } 
}

Or if you can, that is, if your browser supports it, use Array.filter, which is much more terse:

如果可以,也就是说,如果你的浏览器支持它,使用数组。过滤器,更简洁:

var result = array.filter(function (obj) {
  return obj.name === "string 1";
})[0];

#7


9  

New answer

I added the prop as a parameter, to make it more general and reusable

我添加了道具作为参数,使它更通用和可重用

/**
 * Represents a search trough an array.
 * @function search
 * @param {Array} array - The array you wanna search trough
 * @param {string} key - The key to search for
 * @param {string} [prop] - The property name to find it in
 */

function search(array, key, prop){
    // Optional, but fallback to key['name'] if not selected
    prop = (typeof prop === 'undefined') ? 'name' : prop;    

    for (var i=0; i < array.length; i++) {
        if (array[i][prop] === key) {
            return array[i];
        }
    }
}

Usage:

用法:

var array = [
    { 
        name:'string 1', 
        value:'this', 
        other: 'that' 
    },
    { 
        name:'string 2', 
        value:'this', 
        other: 'that' 
    }
];

search(array, 'string 1');
// or for other cases where the prop isn't 'name'
// ex: prop name id
search(array, 'string 1', 'id');

Mocha test:

摩卡测试:

var assert = require('chai').assert;

describe('Search', function() {
    var testArray = [
        { 
            name: 'string 1', 
            value: 'this', 
            other: 'that' 
        },
        { 
            name: 'string 2', 
            value: 'new', 
            other: 'that' 
        }
    ];

    it('should return the object that match the search', function () {
        var name1 = search(testArray, 'string 1');
        var name2 = search(testArray, 'string 2');

        assert.equal(name1, testArray[0]);
        assert.equal(name2, testArray[1]);

        var value1 = search(testArray, 'this', 'value');
        var value2 = search(testArray, 'new', 'value');

        assert.equal(value1, testArray[0]);
        assert.equal(value2, testArray[1]);
    });

    it('should return undefined becuase non of the objects in the array have that value', function () {
        var findNonExistingObj = search(testArray, 'string 3');

        assert.equal(findNonExistingObj, undefined);
    });

    it('should return undefined becuase our array of objects dont have ids', function () {
        var findById = search(testArray, 'string 1', 'id');

        assert.equal(findById, undefined);
    });
});

test results:

测试结果:

Search
    ✓ should return the object that match the search
    ✓ should return undefined becuase non of the objects in the array have that value
    ✓ should return undefined becuase our array of objects dont have ids


  3 passing (12ms)

Old answer - removed due to bad practices

if you wanna know more why it's bad practice then see this article:

如果你想知道为什么这是不好的做法,那么看看这篇文章:

Why is extending native objects a bad practice?

为什么扩展本机对象是不好的做法?

Prototype version of doing an array search:

做数组搜索的原型版本:

Array.prototype.search = function(key, prop){
    for (var i=0; i < this.length; i++) {
        if (this[i][prop] === key) {
            return this[i];
        }
    }
}

Usage:

用法:

var array = [
    { name:'string 1', value:'this', other: 'that' },
    { name:'string 2', value:'this', other: 'that' }
];

array.search('string 1', 'name');

#8


5  

With a foreach:

foreach:

array.forEach((item, i) => {
    if (item.name === 'string 1') {
        return item;
    }
});

#9


5  

One line answer. You can use filter function to get result.

一行的答案。您可以使用filter函数来获取结果。

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

console.log(array.filter(function(arr){return arr.name == 'string 1'})[0]);

#10


4  

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

var foundValue = array.filter(obj=>obj.name==='string 1');

console.log(foundValue);

#11


3  

You can do it with a simple loop:

你可以用一个简单的循环来做:

var obj = null;    
for (var i = 0; i < array.length; i++) {
    if (array[i].name == "string 1") {
        obj = array[i];
        break;
    }
}

#12


3  

Another way (to aid @NullUserException and @Wexoni's comments) is to retrieve the object's index in the array and then go from there:

另一种方法(帮助@NullUserException和@Wexoni注释)是检索数组中的对象索引,然后从那里开始:

var index = array.map(function(obj){ return obj.name; }).indexOf('name-I-am-looking-for');
// Then we can access it to do whatever we want
array[index] = {name: 'newName', value: 'that', other: 'rocks'};

#13


2  

Similar to previous answers I used the following:

与之前的回答类似:

    Array.prototype.getIemtByParam = function(paramPair) {
      var key = Object.keys(paramPair)[0];
      return this.find(function(item){return ((item[key] == paramPair[key]) ? true: false)});
    }

usage:

用法:

myArray.getIemtByParam(
    {name: 'Sasha'}
);

#14


1  

if you are using jQuery try $.grep().

如果您正在使用jQuery,请尝试$.grep()。

http://api.jquery.com/jquery.grep/

http://api.jquery.com/jquery.grep/

#15


1  

Are you looking for generic Search(Filter) across the item in the object list without specifying the item key

您是否在没有指定项键的情况下跨对象列表中的项寻找通用搜索(Filter)

Input

输入

var productList = [{category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'}, {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'}, {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'}, {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'}, {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'}, {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}]
function customFilter(objList, text){
if(undefined === text || text === '' ) return objList;
return objList.filter(product => {
    let flag;
    for(let prop in product){
        flag = false;
        flag = product[prop].toString().indexOf(text) > -1;
        if(flag)
        break;
    }
return flag;
});}

Execute

执行

customFilter(productList, '$9');

在Javascript对象数组中查找值[duplicate]

#16


1  

Considering you have following snippet:

考虑到您有以下片段:

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

You can use the following function to search for items

您可以使用以下函数搜索项目

const search = what => array.find(element => element.name === what);

And you can check whether the item was found or not.

你可以检查物品是否被找到。

if (search("string 1")) {
    console.log(search.value, search.other);
} else {
    console.log('No result found');
}

#17


0  

Here is the solution for search and replace

这里是搜索和替换的解决方案。

function searchAndUpdate(name,replace){
    var obj = array.filter(function ( obj ) {
        return obj.name === name;
    })[0];
    obj.name = replace;
}

searchAndUpdate("string 2","New String 2");

#18


0  

function getValue(){
    for(var i = 0 ; i< array.length; i++){
        var obj = array[i];
        var arr = array["types"];
        for(var j = 0; j<arr.length;j++ ){
            if(arr[j] == "value"){
                return obj;
            }
        }

    }
}

#19


0  

You can use query-objects from npm. You can search an array of objects using filters.

您可以使用npm中的查询对象。您可以使用过滤器搜索对象数组。

const queryable = require('query-objects');

const users = [
    {
      firstName: 'George',
      lastName: 'Eracleous',
      age: 28
    },
    {
      firstName: 'Erica',
      lastName: 'Archer',
      age: 50
    },
    {
      firstName: 'Leo',
      lastName: 'Andrews',
      age: 20
    }
];

const filters = [
    {
      field: 'age',
      value: 30,
      operator: 'lt'
    },
    {
      field: 'firstName',
      value: 'Erica',
      operator: 'equals'
    }
];

// Filter all users that are less than 30 years old AND their first name is Erica
const res = queryable(users).and(filters);

// Filter all users that are less than 30 years old OR their first name is Erica
const res = queryable(users).or(filters);

#20


0  

This answer is good for typescript / Angular 2, 4, 5+

这个答案适用于打字稿/角2、4、5+

I got this answer with the help of @rujmah answer above. His answer brings in the array count... and then find's the value and replaces it with another value...

我通过上面@rujmah的答案得到了这个答案。他的回答带来了数数……然后找到这个值,用另一个值替换它……

What this answer does is simply grabs the array name that might be set in another variable via another module / component... in this case the array I build had a css name of stay-dates. So what this does is extract that name and then allows me to set it to another variable and use it like so. In my case it was an html css class.

这个答案所做的只是简单地获取一个数组名,它可以通过另一个模块/组件在另一个变量中设置。在这种情况下,我构建的数组有一个驻留日期的css名称。这就是提取那个名字然后让我把它设置成另一个变量,然后像这样使用它。在我的例子中,它是一个html css类。

let obj = this.highlightDays.find(x => x.css); let index = this.highlightDays.indexOf(obj); console.log('here we see what hightlightdays is ', obj.css); let dayCss = obj.css;

让obj = this.highlightDays。找到(x = > x.css);让指数= this.highlightDays.indexOf(obj);控制台。log(在这里我们看到什么是hightlightdays, object .css);让dayCss = obj.css;

#1


121  

You can loop over the array and test for that property:

您可以对数组进行循环,并对该属性进行测试:

function search(nameKey, myArray){
    for (var i=0; i < myArray.length; i++) {
        if (myArray[i].name === nameKey) {
            return myArray[i];
        }
    }
}

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

var resultObject = search("string 1", array);

#2


350  

Finding the array element:

let arr = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

let obj = arr.find(o => o.name === 'string 1');

console.log(obj);


Replacing the array element:

let arr = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

let obj = arr.find((o, i) => {
    if (o.name === 'string 1') {
        arr[i] = { name: 'new string', value: 'this', other: 'that' };
        return true; // stop searching
    }
});

console.log(arr);

#3


88  

In ES6 you can use Array.prototype.find(predicate, thisArg?) like so:

在ES6中,可以使用Array.prototype。找到(谓词,thisArg ?)一样:

array.find(x => x.name === 'string 1')

http://exploringjs.com/es6/ch_arrays.html#_searching-for-array-elements https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

http://exploringjs.com/es6/ch_arrays.html _searching-for-array-elements https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

To then replace said object (and use another cool ES6 method fill) you could do something like:

然后替换上述对象(并使用另一种很酷的ES6方法填充),您可以执行以下操作:

let obj = array.find(x => x.name === 'string 1');
let index = array.indexOf(obj);
array.fill(obj.name='some new string', index, index++);

#4


20  

with underscore.js use the findWhere method:

与强调。js使用findWhere方法:

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];


var result = _.findWhere(array, {name: 'string 1'});

console.log(result.name);

See this in JSFIDDLE

看到这在JSFIDDLE

#5


16  

As per ECMAScript 6, you can use the findIndex function.

根据ECMAScript 6,您可以使用findIndex函数。

array[array.findIndex(x => x.name == 'string 1')]

#6


11  

Either use a simple for-loop:

或者使用简单的for-loop:

var result = null;
for (var i = 0; i < array.length; i++) { 
  if (array[i].name === "string 1") { 
    result = array[i];
    break;
  } 
}

Or if you can, that is, if your browser supports it, use Array.filter, which is much more terse:

如果可以,也就是说,如果你的浏览器支持它,使用数组。过滤器,更简洁:

var result = array.filter(function (obj) {
  return obj.name === "string 1";
})[0];

#7


9  

New answer

I added the prop as a parameter, to make it more general and reusable

我添加了道具作为参数,使它更通用和可重用

/**
 * Represents a search trough an array.
 * @function search
 * @param {Array} array - The array you wanna search trough
 * @param {string} key - The key to search for
 * @param {string} [prop] - The property name to find it in
 */

function search(array, key, prop){
    // Optional, but fallback to key['name'] if not selected
    prop = (typeof prop === 'undefined') ? 'name' : prop;    

    for (var i=0; i < array.length; i++) {
        if (array[i][prop] === key) {
            return array[i];
        }
    }
}

Usage:

用法:

var array = [
    { 
        name:'string 1', 
        value:'this', 
        other: 'that' 
    },
    { 
        name:'string 2', 
        value:'this', 
        other: 'that' 
    }
];

search(array, 'string 1');
// or for other cases where the prop isn't 'name'
// ex: prop name id
search(array, 'string 1', 'id');

Mocha test:

摩卡测试:

var assert = require('chai').assert;

describe('Search', function() {
    var testArray = [
        { 
            name: 'string 1', 
            value: 'this', 
            other: 'that' 
        },
        { 
            name: 'string 2', 
            value: 'new', 
            other: 'that' 
        }
    ];

    it('should return the object that match the search', function () {
        var name1 = search(testArray, 'string 1');
        var name2 = search(testArray, 'string 2');

        assert.equal(name1, testArray[0]);
        assert.equal(name2, testArray[1]);

        var value1 = search(testArray, 'this', 'value');
        var value2 = search(testArray, 'new', 'value');

        assert.equal(value1, testArray[0]);
        assert.equal(value2, testArray[1]);
    });

    it('should return undefined becuase non of the objects in the array have that value', function () {
        var findNonExistingObj = search(testArray, 'string 3');

        assert.equal(findNonExistingObj, undefined);
    });

    it('should return undefined becuase our array of objects dont have ids', function () {
        var findById = search(testArray, 'string 1', 'id');

        assert.equal(findById, undefined);
    });
});

test results:

测试结果:

Search
    ✓ should return the object that match the search
    ✓ should return undefined becuase non of the objects in the array have that value
    ✓ should return undefined becuase our array of objects dont have ids


  3 passing (12ms)

Old answer - removed due to bad practices

if you wanna know more why it's bad practice then see this article:

如果你想知道为什么这是不好的做法,那么看看这篇文章:

Why is extending native objects a bad practice?

为什么扩展本机对象是不好的做法?

Prototype version of doing an array search:

做数组搜索的原型版本:

Array.prototype.search = function(key, prop){
    for (var i=0; i < this.length; i++) {
        if (this[i][prop] === key) {
            return this[i];
        }
    }
}

Usage:

用法:

var array = [
    { name:'string 1', value:'this', other: 'that' },
    { name:'string 2', value:'this', other: 'that' }
];

array.search('string 1', 'name');

#8


5  

With a foreach:

foreach:

array.forEach((item, i) => {
    if (item.name === 'string 1') {
        return item;
    }
});

#9


5  

One line answer. You can use filter function to get result.

一行的答案。您可以使用filter函数来获取结果。

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

console.log(array.filter(function(arr){return arr.name == 'string 1'})[0]);

#10


4  

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

var foundValue = array.filter(obj=>obj.name==='string 1');

console.log(foundValue);

#11


3  

You can do it with a simple loop:

你可以用一个简单的循环来做:

var obj = null;    
for (var i = 0; i < array.length; i++) {
    if (array[i].name == "string 1") {
        obj = array[i];
        break;
    }
}

#12


3  

Another way (to aid @NullUserException and @Wexoni's comments) is to retrieve the object's index in the array and then go from there:

另一种方法(帮助@NullUserException和@Wexoni注释)是检索数组中的对象索引,然后从那里开始:

var index = array.map(function(obj){ return obj.name; }).indexOf('name-I-am-looking-for');
// Then we can access it to do whatever we want
array[index] = {name: 'newName', value: 'that', other: 'rocks'};

#13


2  

Similar to previous answers I used the following:

与之前的回答类似:

    Array.prototype.getIemtByParam = function(paramPair) {
      var key = Object.keys(paramPair)[0];
      return this.find(function(item){return ((item[key] == paramPair[key]) ? true: false)});
    }

usage:

用法:

myArray.getIemtByParam(
    {name: 'Sasha'}
);

#14


1  

if you are using jQuery try $.grep().

如果您正在使用jQuery,请尝试$.grep()。

http://api.jquery.com/jquery.grep/

http://api.jquery.com/jquery.grep/

#15


1  

Are you looking for generic Search(Filter) across the item in the object list without specifying the item key

您是否在没有指定项键的情况下跨对象列表中的项寻找通用搜索(Filter)

Input

输入

var productList = [{category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'}, {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'}, {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'}, {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'}, {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'}, {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}]
function customFilter(objList, text){
if(undefined === text || text === '' ) return objList;
return objList.filter(product => {
    let flag;
    for(let prop in product){
        flag = false;
        flag = product[prop].toString().indexOf(text) > -1;
        if(flag)
        break;
    }
return flag;
});}

Execute

执行

customFilter(productList, '$9');

在Javascript对象数组中查找值[duplicate]

#16


1  

Considering you have following snippet:

考虑到您有以下片段:

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

You can use the following function to search for items

您可以使用以下函数搜索项目

const search = what => array.find(element => element.name === what);

And you can check whether the item was found or not.

你可以检查物品是否被找到。

if (search("string 1")) {
    console.log(search.value, search.other);
} else {
    console.log('No result found');
}

#17


0  

Here is the solution for search and replace

这里是搜索和替换的解决方案。

function searchAndUpdate(name,replace){
    var obj = array.filter(function ( obj ) {
        return obj.name === name;
    })[0];
    obj.name = replace;
}

searchAndUpdate("string 2","New String 2");

#18


0  

function getValue(){
    for(var i = 0 ; i< array.length; i++){
        var obj = array[i];
        var arr = array["types"];
        for(var j = 0; j<arr.length;j++ ){
            if(arr[j] == "value"){
                return obj;
            }
        }

    }
}

#19


0  

You can use query-objects from npm. You can search an array of objects using filters.

您可以使用npm中的查询对象。您可以使用过滤器搜索对象数组。

const queryable = require('query-objects');

const users = [
    {
      firstName: 'George',
      lastName: 'Eracleous',
      age: 28
    },
    {
      firstName: 'Erica',
      lastName: 'Archer',
      age: 50
    },
    {
      firstName: 'Leo',
      lastName: 'Andrews',
      age: 20
    }
];

const filters = [
    {
      field: 'age',
      value: 30,
      operator: 'lt'
    },
    {
      field: 'firstName',
      value: 'Erica',
      operator: 'equals'
    }
];

// Filter all users that are less than 30 years old AND their first name is Erica
const res = queryable(users).and(filters);

// Filter all users that are less than 30 years old OR their first name is Erica
const res = queryable(users).or(filters);

#20


0  

This answer is good for typescript / Angular 2, 4, 5+

这个答案适用于打字稿/角2、4、5+

I got this answer with the help of @rujmah answer above. His answer brings in the array count... and then find's the value and replaces it with another value...

我通过上面@rujmah的答案得到了这个答案。他的回答带来了数数……然后找到这个值,用另一个值替换它……

What this answer does is simply grabs the array name that might be set in another variable via another module / component... in this case the array I build had a css name of stay-dates. So what this does is extract that name and then allows me to set it to another variable and use it like so. In my case it was an html css class.

这个答案所做的只是简单地获取一个数组名,它可以通过另一个模块/组件在另一个变量中设置。在这种情况下,我构建的数组有一个驻留日期的css名称。这就是提取那个名字然后让我把它设置成另一个变量,然后像这样使用它。在我的例子中,它是一个html css类。

let obj = this.highlightDays.find(x => x.css); let index = this.highlightDays.indexOf(obj); console.log('here we see what hightlightdays is ', obj.css); let dayCss = obj.css;

让obj = this.highlightDays。找到(x = > x.css);让指数= this.highlightDays.indexOf(obj);控制台。log(在这里我们看到什么是hightlightdays, object .css);让dayCss = obj.css;