在Javascript中的对象数组中查找值

在Javascript中的对象数组中查找值,javascript,arrays,Javascript,Arrays,我知道以前也有人问过类似的问题,但这次有点不同。我有一个未命名对象数组,其中包含一个命名对象数组,我需要获取“name”为“string1”的对象。下面是一个示例数组 var array = [ { name:"string 1", value:"this", other: "that" }, { name:"string 2", value:"this", other: "that" } ]; 更新:我应该早点说,但是一旦我找到它,我想用一个编辑过的对象替换它。你可以通过一个

我知道以前也有人问过类似的问题,但这次有点不同。我有一个未命名对象数组,其中包含一个命名对象数组,我需要获取“name”为“string1”的对象。下面是一个示例数组

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

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

你可以通过一个简单的循环来完成:

var obj = null;    
for (var i = 0; i < array.length; i++) {
    if (array[i].name == "string 1") {
        obj = array[i];
        break;
    }
}
var obj=null;
对于(var i=0;i
您可以在阵列上循环并测试该属性:

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);
函数搜索(名称键,myArray){
对于(var i=0;i
使用一个简单的
循环:

var result = null;
for (var i = 0; i < array.length; i++) { 
  if (array[i].name === "string 1") { 
    result = array[i];
    break;
  } 
}
查找数组元素:
让arr=[
{name:“string 1”,value:“this”,other:“that”},
{name:“string 2”,value:“this”,other:“that”}
];
让obj=arr.find(o=>o.name=='string1');

控制台日志(obj)这是搜索和替换的解决方案

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

searchAndUpdate("string 2","New String 2");
函数getValue(){
对于(var i=0;i对于带有下划线.js的(var j=0;j),请使用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);
请参见

新答案 我添加了道具作为参数,以使其更通用和可重用

/**
 * 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];
        }
    }
}
摩卡咖啡测试:

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);
    });
});
测试结果:

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)
旧答案-由于不良做法而删除 如果您想了解更多为什么这是一种不好的做法,请参阅本文:

执行数组搜索的原型版本:

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

与前面的答案类似,我使用了以下内容:

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

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

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

另一种方法(帮助@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'};

ES6中,您可以使用
Array.prototype.find(predicate,thisArg?
如下所示:

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

然后,要更换所述对象(并使用另一种凉爽的ES6方法
fill
),您可以执行以下操作:

let obj = array.find(x => x.name === 'string 1');
let index = array.indexOf(obj);
array.fill(obj.name='some new string', index, index++);
您可以从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);
是否在不指定项目键的情况下查找对象列表中项目的通用搜索(筛选器)

输入

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;
});}
执行

customFilter(productList, '$9');

使用foreach:

let itemYouWant = null;
array.forEach((item) => {
    if (item.name === 'string 1') {
        itemYouWant = item;
    }
});
console.log(itemYouWant);

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

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

这个答案适用于打字脚本/角度2,4,5+

我在上面@rujmah answer的帮助下得到了这个答案。他的答案带来了数组计数…然后找到值并用另一个值替换它

这个答案的作用是简单地获取可能通过另一个模块/组件在另一个变量中设置的数组名称…在本例中,我构建的数组有一个css名称stay dates。因此,这可以提取该名称,然后允许我将其设置为另一个变量并像这样使用。在我的示例中,它是一个html css类

让obj=this.highlightDays.find(x=>x.css);
设index=this.highlightDays.indexOf(obj);
log('这里我们看到hightlightdays是什么',obj.css);
让dayCss=obj.css;

一行回答。 您可以使用filter函数来获得结果

var数组=[
{name:“string 1”,value:“this”,other:“that”},
{name:“string 2”,value:“this”,other:“that”}
];

console.log(array.filter(函数(arr){return arr.name=='string 1'})[0]);
考虑到您有以下代码段:

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];
您可以使用以下功能搜索项目

const search = what => array.find(element => element.name === what);
您可以检查是否找到了该项目

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


如果您知道它在哪里,您可以使用
array[0]['name']
空对象的用途是什么?@Bergi这取决于代码的用途。那么
null
怎么样?对我来说更有意义,谢谢。只
未定义的
也可以,imho…@Bergi可能
null
对未找到的元素更具描述性。当返回obj时,我如何获得其在orig中的位置inal array?@VedranMaricevic。使用array.fill()你永远不应该修改本机对象的原型。让谷歌搜索一下为什么这不好,有很多文章和stackoverflow问题。这个问题的答案给出了一个很好的理由()到目前为止对我来说效果很好,但这可能是一种反模式。它确实起作用,但是的,它是一种反模式和坏模式practice@silverlight513还添加了mocha测试和结果+1来添加测试,它们总是值得添加的。我不得不说,尽管西姆·维达斯使用过滤器似乎是一种更干净的方法,可以通过数组循环到find对象(imo)。将函数更改为this
search(nameKey,prop,myArray)
,将if子句更改为this
if(myArray[i][prop]==nameKey){
在object中搜索任何属性也有一个很小的实用程序,在整数值的情况下调用,use==我在搜索如何在Angular2模板中使用find来设置属性时,碰巧找到了这个答案。最后,这篇文章将ES6 find与管道很好地结合了起来……如果它只是一个值,这里,您还可以将其简写为:array.find(x=>x.name==“string1”).name=“一些新字符串”;谢谢你,si。!!能够使用此代码在数组中查找某些内容,然后将其从名称中取出并使用变量…我将在下面发布我的答案这里已经有方法可用于返回索引而不是对象,从而避免再次使用
indexOf
。我只能使用==,而不是
array[array.findIndex(x => x.name == 'string 1')]
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);
var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];
const search = what => array.find(element => element.name === what);
if (search("string 1")) {
    console.log(search.value, search.other);
} else {
    console.log('No result found');
}