539

以前にも同様の質問があったことは知っていますが、これは少し異なります。名前付きオブジェクトの配列を含む名前のないオブジェクトの配列があり、「名前」が「文字列 1」であるオブジェクトを取得する必要があります。以下は配列の例です。

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

更新:先に言っておくべきだったのですが、見つかったら編集済みのオブジェクトに置き換えたいと思います。

4

20 に答える 20

1174

配列要素の検索:

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);


配列要素の置き換え:

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);

于 2012-09-17T15:24:48.013 に答える
307

配列をループして、そのプロパティをテストできます。

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);
于 2012-09-17T15:23:36.437 に答える
202

ES6 では、次Array.prototype.find(predicate, 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

次に、上記のオブジェクトを置き換える(そして別のクールな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++);
于 2016-07-21T09:34:37.427 に答える
22

underscore.jsfindWhere メソッドを使用します。

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);

JSFIDDLEでこれを参照してください

于 2015-07-31T14:16:29.157 に答える
22

単純なfor-loopを使用します。

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

または、できる場合、つまりブラウザがサポートしている場合は、Array.filterより簡潔な を使用します。

var result = array.filter(function (obj) {
  return obj.name === "string 1";
})[0];
于 2012-09-17T15:24:24.733 に答える
13

新しい答え

より一般的で再利用可能にするために、小道具をパラメーターとして追加しました

/**
 * 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 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');

モカテスト:

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];
        }
    }
}

使用法:

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

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

于 2015-10-13T08:05:31.350 に答える
7

簡単なループでそれを行うことができます:

var obj = null;    
for (var i = 0; i < array.length; i++) {
    if (array[i].name == "string 1") {
        obj = array[i];
        break;
    }
}
于 2012-09-17T15:21:18.717 に答える
4

別の方法 (@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'};
于 2016-06-09T20:53:47.960 に答える
3

以前の回答と同様に、次を使用しました。

    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'}
);
于 2015-11-20T11:35:51.627 に答える
2

これが検索と置換のソリューションです

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

searchAndUpdate("string 2","New String 2");
于 2014-06-17T12:05:35.833 に答える
1

jQuery を使用している場合は、$.grep() を試してください。

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

于 2016-05-27T18:16:09.930 に答える
0

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);
于 2016-08-05T09:41:06.193 に答える