6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javascriptでオブジェクトの配列から特定の値を持つ要素を抜き出す

Last updated at Posted at 2018-10-28

よく使うのでメモ。
次のようなオブジェクトの配列(連想配列の配列)があった場合、

//オブジェクトの配列
var objArray = [
    {'name':'apple','price':300, 'weight':100},
    {'name':'orange','price':200 , 'weight': 50},
    {'name':'banana','price':100, 'weight': 120}
];

###関数

/**
* @function Array.prototype.pickObj オブジェクトの配列から要素を抜き出す
*/
if(!Array.prototype.pickObj){
    Object.defineProperty(Array.prototype, "pickObj", {
        configurable: false,
        enumerable: false,
        writable: false,
        /**
        * @string keys オブジェクトのキー
        * @param patterns 探索する値
        */
        value: function(key,...patterns) {
           return this.filter(e => patterns.includes(e[key]));
        }
    });
}

※2018/10/31修正
上記方法2及び3については、当初、inArray処理を無骨にも以下のように定義していたのですが、ttatsfさんコメントよりArray.prototype.includes (ES2016) を採用しました。

const inArray =  (value,array) => [].indexOf.call(array,value) > -1;  //inArrayの定義

###処理→出力

var objArray = [
    {'name':'apple','price':300, 'weight':100},
    {'name':'orange','price':200 , 'weight': 50},
    {'name':'banana','price':100, 'weight': 120}
];

console.log(objArray.pickObj('price',300)); //価格が300に等しい
console.log(objArray.pickObj('price',100, 200)); //価格が100または200に等しい 

###結果

{'name':'apple','price':300}
[
    {'name':'orange','price':200, 'weight':50},
    {'name':'banana','price':100, 'weight': 120}
]
6
5
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?