根据Javascript中的列表从Json中提取字段

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (10)

我正在尝试从Json响应中提取一些字段并将它们推送到Javascript数组中。我希望可以配置字段的选择。这是我正在做的事情:

将此视为我的JSON字符串:

{
    "id" : "1234",
    "orderNumber" : "1196",
    "createdOn" : "2019-07-02T12:03:39.697Z",
    "modifiedOn" : "2019-07-02T12:25:52.126Z",
    "testmode" : false,
    "customerEmail" : "a@b.com",
    "billingAddress" : {
      "firstName" : "John",
      "lastName" : "Doe",
      "address1" : "Wall Street",
      "address2" : null,
      "city" : "NYC",
      "state" : "NY",
      "countryCode" : "US",
      "postalCode" : "12345",
      "phone" : "1122334455"
    }
}

假设我想提取一些字段(在FIELDS变量中定义)并将它们推入数组中。

# NOTE: the variable `data` here is my json object 

var FIELDS = ['id', 'orderNumber', 'customerEmail', 'billingAddress.firstName', 'billingAddress.lastName']

var lineItem = []

# parse the data (my Json object)
for (var i = 0; i < FIELDS.length; i++){
  lineItem.push(data[FIELDS[i]])
}

所以,这似乎对第一级(id,orderNumber和customerEmail)工作正常,但不适用于billingAddress.firstname等。这就是我想知道的。

我的目的是能够修改FIELDS变量中的定义,而无需对代码中的逻辑进行任何更改。

希望这是有道理的。谢谢!

提问于
用户回答回答于

只要密钥名称中没有句点,这将起作用。

var data = {
    "id" : "1234",
    "orderNumber" : "1196",
    "createdOn" : "2019-07-02T12:03:39.697Z",
    "modifiedOn" : "2019-07-02T12:25:52.126Z",
    "testmode" : false,
    "customerEmail" : "a@b.com",
    "billingAddress" : {
      "firstName" : "John",
      "lastName" : "Doe",
      "address1" : "Wall Street",
      "address2" : null,
      "city" : "NYC",
      "state" : "NY",
      "countryCode" : "US",
      "postalCode" : "12345",
      "phone" : "1122334455"
    }
};

var FIELDS = ['id', 'orderNumber', 'customerEmail', 'billingAddress.firstName', 'billingAddress.lastName'];

var lineItem = [];
for (var i = 0; i < FIELDS.length; i++){
  let obj = data;
  let parts = FIELDS[i].split(".");
  while(parts.length) obj = obj[parts.shift()];
  lineItem.push(obj)
}

console.log(lineItem);
用户回答回答于

您只需要一个将该路径拆分.并遍历JSON数据的函数。有了它,你可以map()在你的领域。

let data = {"id" : "1234","orderNumber" : "1196","createdOn" : "2019-07-02T12:03:39.697Z","modifiedOn" : "2019-07-02T12:25:52.126Z","testmode" : false,"customerEmail" : "a@b.com","billingAddress" : {"firstName" : "John","lastName" : "Doe","address1" : "Wall Street","address2" : null,"city" : "NYC","state" : "NY","countryCode" : "US","postalCode" : "12345","phone" : "1122334455"}}
var FIELDS = ['id', 'orderNumber', 'customerEmail', 'billingAddress.firstName', 'billingAddress.lastName']

// split an traverse
const getFromPath = (path, data) => path.split('.')
      .reduce((curr, p) => curr && curr[p], data) // check for curr incase path is undefined
      
console.log(FIELDS.map(p => getFromPath(p, data)))

如果在对象中找不到遍历的任何部分,则该函数getFromPath将返回undefined

扫码关注云+社区

领取腾讯云代金券