使用lodash压平嵌套对象

时间:2017-03-07 10:09:14

标签: javascript ecmascript-6 lodash

压扁,平坦深度或平坦的lodashDepth只接受数组。如何展平嵌套对象?

var data = {
  "dates": {
    "expiry_date": "30 sep 2018",
    "available": "30 sep 2017",
    "min_contract_period": [{
      "id": 1,
      "name": "1 month",
      "value": false
    }, {
      "id": 2,
      "name": "2 months",
      "value": true
    }, {
      "id": 3,
      "name": "3 months",
      "value": false
    }]
  },
  "price": {
    "curreny": "RM",
    "min": 1500,
    "max": 2000
  }
}

我希望嵌套属性成为第一级,比如expiry_date应该是1级,而不是日期,我认为日期应该消失,不再需要它了。我可以手动完成,使用map(),但我希望使用lodash来简化任务。

6 个答案:

答案 0 :(得分:10)

最简单的解决方案之一是,将嵌套对象与父对象合并,

_.merge(data, data.dates);

这会将所有data.dates属性带入data。然后删除data.dates

delete data.dates

答案 1 :(得分:5)

ES6版本:

var data = {
  "dates": {
    "expiry_date": "30 sep 2018",
    "available": "30 sep 2017",
    "min_contract_period": [{
      "id": 1,
      "name": "1 month",
      "value": false
    }, {
      "id": 2,
      "name": "2 months",
      "value": true
    }, {
      "id": 3,
      "name": "3 months",
      "value": false
    }]
  },
  "price": {
    "curreny": "RM",
    "min": 1500,
    "max": 2000
  }
};

var {dates: {expiry_date, ...dates}, ...rest} = data;
var flatData = {dates, expiry_date, ...rest}
console.log(flatData)

要注意的一件事是,您必须小心嵌套深层的销毁。在此示例中,如果data.datesundefined,而您将尝试对其进行解构,则将引发错误。

答案 2 :(得分:1)

您可以.merge() .get()_.pick()的结果:



var data = {"dates": {"expiry_date": "30 sep 2018","available": "30 sep 2017","min_contract_period": [{"id": 1,"name": "1 month","value": false}, {"id": 2,"name": "2 months","value": true}, {"id": 3,"name": "3 months","value": false}]},"price": {"curreny": "RM","min": 1500,"max": 2000}},
    result = _.merge(_.get(data, 'dates'), _.pick(data, 'price'));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

此对象使用嵌套对象和任意深度的数组来展平对象。结果对象中的键是输入对象中属性的完整路径

# Create dummy dataset
X0 <- c(1,2,3)
X1 <- c(10,20,30)
X2 <- c(100,200,300)
X3 <- c(1000,2000,3000)
df <- data.frame(X0,X1,X2,X3)

# Calculate df$pred
df$pred <- X0 + 1.37*X1 - 3.23*X2 + 1.74*X3

答案 4 :(得分:0)

来自Andreyanswer

function flattenObject(o, prefix = '', result = {}, keepNull = true) {
  if (_.isString(o) || _.isNumber(o) || _.isBoolean(o) || (keepNull && _.isNull(o))) {
    result[prefix] = o;
    return result;
  }

  if (_.isArray(o) || _.isPlainObject(o)) {
    for (let i in o) {
      let pref = prefix;
      if (_.isArray(o)) {
        pref = pref + `[${i}]`;
      } else {
        if (_.isEmpty(prefix)) {
          pref = i;
        } else {
          pref = prefix + '.' + i;
        }
      }
      flattenObject(o[i], pref, result, keepNull);
    }
    return result;
  }
  return result;
}

答案 5 :(得分:0)

如果您需要展平整个对象,不仅要展平其“ dates”属性,这样的方法应该可以工作,甚至不需要lodash:

function flattenObject(obj) {
  const result = {};

  Object.values(obj).forEach(nestedObject => {
    Object.assign(result, nestedObject);
  });

  return result;
}