LoginSignup
3
10

More than 5 years have passed since last update.

Javascriptでオブジェクトの配列の追加・更新・削除

Last updated at Posted at 2018-09-10

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

var commodity = [
    {"name":"apple","price":300},
    {"name":"orange","price":200}
];

1 更新・追加

関数

/**
* @function Array.prototype.update オブジェクトの配列要素を更新・追加する
*/
if(!Array.prototype.update){
    Object.defineProperty(Array.prototype,'update', {
        configurable: false,
        enumerable: false,
        writable: false,
        /**
        * @param keyProperty 探索するキー
        * @param keyValue 探索するの値
        * @param newProperty 新しいキー
        * @param newValue 新しい値
        */
        value: function(keyProperty,keyValue,newProperty,newValue) {
            //オブジェクトの配列であるか確認
            if(Object.prototype.toString.call(this[0])!=='[object Object]'){
                console.log('TypeError: Other than an array of object was passed.');
                return false;
            }
            //配列内に目的の要素があれば値を更新し、なければ新しい要素を追加
            if(this.some(e => e[keyProp]===keyVal)){
                this.forEach(e => e[keyProp]===keyVal ? e[newProp]=newVal : false);
                //または 
                //this.map(e => e[keyProp]===keyVal ? Object.assign(e,{[newProp]:newVal}) : e);
            }else{
                this.push({[keyProp]:keyVal,[newProp]:newVal})
            }
            return this;
        }
    });
}

処理→出力

var commodity = [
    {'name':'apple','price':300},
    {'name':'orange','price':200}
];
products.update('name','orange','price',250);
products.update('name','banana','price',200);
console.log(JSON.stringify(products, null, '\t'));

結果

[
    {"name":"apple","price":300},
    {"name":"orange","price":250},
    {"name":"banana","price":200}
]

2 削除

関数

/**
* @function Array.prototype.delete オブジェクトの配列要素を削除する
*/
if(!Array.prototype.delete){
    Object.defineProperty(Array.prototype,'delete', {
        configurable: false,
        enumerable: false,
        writable: false,
        /**
        * @param keyProperty 探索するキー
        * @param keyValue 探索するの値
        */
        value: function(keyProperty,keyValue) {
             //オブジェクトの配列であるか確認
            if(Object.prototype.toString.call(this[0])!=='[object Object]'){
                console.log('TypeError: Other than an array of object was passed.');
                return false;
            }
            //配列内から目的の要素を見つけたら削除する
            this.forEach((e,i,self)=> e[keyProp]===keyVal ? self.splice(i,1) : false);
            return this;

            //または(非破壊的メソッド)
            //return this.filter(e=>e[keyProp]!==keyVal);
        }
    });
}

処理→出力

var products = [
    {'name':'apple','price':300},
    {'name':'orange','price':200}
];
products.delete('name','orange');
console.log(JSON.stringify(products, null, '\t'));

結果

[
    {"name":"apple","price":300}
]

おまけ

WebStorage等をデータベース的に使いたい場合は、処理の前後に、オブジェクトの配列の読み込み・書き込みを追加する。

//データベース読み込み
var objArray = JSON.parse(localStorage.getItem("objArray"));
//データベース書き込み
localStorage.setItem("objArray", JSON.stringify(objArray));
3
10
0

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
3
10