Map over object preserving keys

后端 未结 12 1456
再見小時候
再見小時候 2020-12-07 14:41

The map function in underscore.js, if called with a javascript object, returns an array of values mapped from the object\'s values.

_.map({one:          


        
12条回答
  •  醉酒成梦
    2020-12-07 15:11

    How about this version in plain JS (ES6 / ES2015)?

    let newObj = Object.assign(...Object.keys(obj).map(k => ({[k]: obj[k] * 3})));
    

    jsbin

    If you want to map over an object recursively (map nested obj), it can be done like this:

    const mapObjRecursive = (obj) => {
      Object.keys(obj).forEach(key => {
        if (typeof obj[key] === 'object') obj[key] = mapObjRecursive(obj[key]);
        else obj[key] = obj[key] * 3;
      });
      return obj;
    };
    

    jsbin

    Since ES7 / ES2016 you can use Object.entries instead of Object.keys like this:

    let newObj = Object.assign(...Object.entries(obj).map([k, v] => ({[k]: v * 3})));
    

提交回复
热议问题