如何在javascript中更改数据方案?

时间:2018-05-10 11:28:11

标签: javascript json

我有以下数据;

{
  "house": {
    "subname1": {
      "active": true,
      "address": "123 street"
    },
    "subname2": {
      "active": true,
      "address": "123 street"
    }
  },
  "business": {
    "example": {
      "active": true,
      "address": "123 street"
    }
  }
}

我想改成这个;

{"type" : "house", "subtype" : "subname1", "active" : true, "address" : "123 street"},
{"type" : "house", "subtype" : "subname2", "active" : true, "address" : "123 street"},
{"type" : "business", "subtype" : "example", "active" : true, "address" : "123 street"}

我用了Lodash。我不确定这是正确的方法。 并且不知道如何添加

    _.map(formData, (r,v,k) => {
      _.map(r, (re,key,ke) => {
        _.map(re, (a,b,c) => {

        newObj["type"] = v;
        newObj["name"] = key;
        //need to be added c object more
        })
      })
    })

以下是我到目前为止所取得的成就。

{
  name: "example",
  type: "business"
}

2 个答案:

答案 0 :(得分:1)

您可以尝试以下

var obj = {"house":{"subname1":{"active":true,"address":"123 street"},"subname2":{"active":true,"address":"123 street"}},"business":{"example":{"active":true,"address":"123 street"}}};

var result = [];
Object.keys(obj).forEach((type) => {
  Object.keys(obj[type]).forEach((subtype) => {
    result.push({
        type : type,
        subtype : subtype,
        ...obj[type][subtype]
    });
  });  
});

console.log(result);

答案 1 :(得分:0)

如果我理解正确,您希望为对象提供名为type的父键。

如果是这样,请尝试这种方式:



var type = {
  "house": {
    "subname1": {
      "active": true,
      "address": "123 street"
    },
    "subname2": {
      "active": true,
      "address": "123 street"
    }
  },
  "business": {
    "example": {
      "active": true,
      "address": "123 street"
    }
  }
}

var object = object || {};
object.type = type;
console.log(object);