首页 > 解决方案 > 使用键排除列表展平 json

问题描述

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

例如

if I have an exclude_keys_array = ["addresses.metadata", "pageToken"] //只会跳过地址的元数据(第二级跳过)

if I have an exclude_keys_array = ["metadata", "pageToken"] //父json的元数据将被跳过(顶级键跳过)

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

代码源:从 JSON 动态生成具有不同列的二维数组

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; }

标签: javascriptarraysjsonmultidimensional-array

解决方案


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

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

推荐阅读