js写法简化

对象var obj={“shopId”:1,“price”:10,“name”:“kobi”,“shopNum”:21,“color”:“red”,“age”:32}
现在要获取obj的age,color,name并加入到一个新的空对象中,写法:var abc={};abc.age=obj.age abc.color=obj.color   abc.name=obj.name   

想问下,这样写法有什么不妥的地方,还有怎么转化成逼格高一些的样式,请帮帮忙,谢谢啦
阅读 3.6k
4 个回答

let { age, color, name } = obj
let abc = { age, color, name }

逼格高一点的啊,你看这样逼格高不高?

const obj = {"shopId":1,"price":10,"name":"kobi","shopNum":21,"color":"red","age":32};

const abc = ['age', 'color', 'name'].reduce((ans, key) => (ans[key] = obj[key], ans), {});

上面的都是新技术,我来一个稳妥点的方法

<script>    
    function test (obj, keys) {
        var result = {};
        for(var a=0; a<keys.length; a++) {
            obj[keys[a]] ? result[keys[a]] = obj[keys[a]] : null;
        }        
        return result;
    }
    
    var obj={
        "shopId": 1,
        "price": 10,
        "name": "kobi",
        "shopNum": 21,
        "color": "red",
        "age":32
    };
    
    var newObj = test(obj, ['age', 'name', 'color']);
    
    console.log(newObj)
</script>

如果可以引入 ramda 库:

const R = require('ramda')
let abc = R.pick(['age', 'name', 'color'], obj)
推荐问题
宣传栏