Keeping only certain properties in a JavaScript object

后端 未结 11 1001
时光说笑
时光说笑 2020-12-20 11:05

I have an object. I would like to modify the object (not clone it) by removing all properties except for certain specific properties. For instance, if I started with this o

11条回答
  •  一整个雨季
    2020-12-20 11:55

    I Made this short solution for case where I have an array with objects.

    so consider the array below?

    arr=[{"a1":"A1","b1":"B1"},{"a1":"Z1","b1":"X1"}];
    console.log(arr);

    I want to keep only "b1" properties of all objects.

    You can use map() and delete for that as follows:

    arr=[{"a1":"A1","b1":"B1"},{"a1":"Z1","b1":"X1"}];
    arr=arr.map(function(d){
            delete d["a1"];
            return d;
    
        });
    console.log(arr);

    result is an array with objects but only "b1" properties.

提交回复
热议问题