【问题标题】:Flattening json with an key exclusion list使用键排除列表展平 json
【发布时间】:2021-10-21 02:56:25
【问题描述】:

我需要展平 json,但想考虑一个不被处理/添加到列表中的 exclude_keys_array 列表

例如

如果我有 exclude_keys_array = ["addresses.metadata", "pageToken"] //只会跳过地址的元数据(二级跳过)

如果我有 exclude_keys_array = ["metadata", "pageToken"] //父json的元数据将被跳过(顶级键跳过)

如何使用排除数组来展平 JSON?

代码来源:Dynamically generate a 2d array from JSON with varying columns

var exlusion_list = ["metadata", "meta", "pageToken"];

var crowds = [{
  "name": [{
    "firstName": "John",
    "middleName": "Joseph",
    "lastName": "Briggs",
  }],
  "addresses": [{
    "type": "home",
    "poBox": "111",
    "city": "City1",
    "postalCode": "1ER001",
    "country": "USA",
  }, {
    "type": "work",
    "poBox": "222",
    "city": "City2",
    "region": "Region2",
    "postalCode": "1ER002",
  }],
  "photos": [{
    "url": "photo.org/person1",
    "default": true,
  }, {
    "url": "imagur.org/person1",
    "default": true,
  }],
  "metadata": [{
    "meta-id": "1234",
  }],
}, {
  "name": [{
    "firstName": "Bill",
    "lastName": "Thatcher",
  }],
  "addresses": [{
    "type": "home",
    "city": "City3",
    "region": "Region3",
    "postalCode": "1ER003",
    "country": "USA",
  }, {
    "type": "work",
    "poBox": "444",
    "region": "Region4",
    "postalCode": "1ER004",
  }, {
    "poBox": "555",
    "region": "Region5",
    "postalCode": "1ER005",
  }],
  "metadata": [{
    "meta-id": "1234",
  }],
}];

function flatten(obj, res = {}, key = '') {
  let add = (d, s) => key ? key + d + s : s;

  if (Array.isArray(obj)) {
    obj.forEach((v, n) => flatten(v, res, add(' #', n + 1)));
  } else if (typeof obj === 'object') {
    Object.entries(obj).forEach(([k, v]) => flatten(v, res, add(': ', k)));
  } else {
    res[key] = obj;
  }
  return res;
}
let flats = crowds.map(obj => flatten(obj));

function combineKeys(objs) {
  let keys = objs.reduce((k, obj) => k.concat(Object.keys(obj)), []);
  return [...new Set(keys)];
}
let keys = combineKeys(flats);

let table = flats.map(f => keys.map(k => f[k] ?? ''));

table.unshift(keys);

console.log({ table });
// document.write(JSON.stringify(table));
.as-console-wrapper { min-height: 100%!important; top: 0; }
// .as-console-wrapper { min-height: 70%!important; bottom: 0; }

【问题讨论】:

    标签: javascript arrays json multidimensional-array


    【解决方案1】:

    一个快速的解决方法是过滤如下的键。我认为有一种更有效的方法可以做到这一点,但我没有深入研究代码。

    let keys = combineKeys(flats).filter(
      key => !exlusion_list.includes(key.split(":")[0].split(" ")[0])
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-05
      • 2017-07-13
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      • 2015-02-06
      相关资源
      最近更新 更多