JSON对象中的嵌套数组,如果不存在则添加键并将值设置为空[重复]

问题描述 投票:0回答:1

目前我在 JSON 对象中嵌套了数组。我想定义

的键和值
  • 联系方式(“电话”:“ ”,“电子邮件”:“ ”,“传真”:“ ”,“网站”:“ ”)
  • 地址为 ("city": " ", "country": " ", "house_number :"", "street name" :"")

如果缺少此键之一,则需要填充为默认键和值,如预期输入中所示。 谁能帮忙用 JavaScript 实现这一点吗?

电流输入

{
    "data": [{
        "name": "John",
        "contact": {
            "phone": "987-654-3210",
            "email": "[email protected]"
        },
        "address": {
            "city": "Berlin",
            "country": "Germany"
        }
    }]
}

预期输入

{
    "data": [{
        "name": "John",
        "contact": {
            "phone": "987-654-3210",
            "email": "[email protected]",
             "fax" : "",
              "website" : ""

        },
        "address": {
            "city": "Berlin",
            "country": "Germany",
            "house_number :"",
            "street name" :""
        }
    }]
}
javascript json nested-loops
1个回答
0
投票

如果您不介意改变原始数组,这里有一个解决方案:

const templates = {
  contact: {
    "phone": "",
    "email": "",
    "fax": "",
    "website": ""
  },
  address: {
    "city": "",
    "country": "",
    "house_number": "",
    "street name": ""
  }
}

source.data.forEach(entry => Object.entries(templates).forEach(([key, template]) => {
  entry[key] ||= {};
  Object.entries(template).forEach(([k, v]) => {
    entry[key][k] ||= v;
  });
}));

const source = {
  "data": [{
    "name": "John",
    "contact": {
      "phone": "987-654-3210",
      "email": "[email protected]"
    },
    "address": {
      "city": "Berlin",
      "country": "Germany"
    }
  }, {
    "name": "Bob",
    "contact": {
      "phone": "123-456-7890",
      "fax": "9876-5432",
      "website": "bob.example.com"
    },
    "address": {
      "city": "NYC",
      "country": "USA",
      "house_number": "701A"
    }
  }]
};

const templates = {
  contact: {
    "phone": "",
    "email": "",
    "fax": "",
    "website": ""
  },
  address: {
    "city": "",
    "country": "",
    "house_number": "",
    "street name": ""
  }
}

source.data.forEach(entry => Object.entries(templates).forEach(([key, template]) => {
  entry[key] ??= {};
  Object.entries(template).forEach(([k, v]) => {
    entry[key][k] ??= v;
  });
}));

console.log(source);

© www.soinside.com 2019 - 2024. All rights reserved.