如何通过JSON密钥的前缀或密钥将JSON密钥分组为新密钥?

时间:2020-10-19 08:49:01

标签: javascript json

所以我有一个类似以下的查询输出(使用knex):

response = [
  {id: 1, source: 'mobile', ms_payment.id: 111, ms_payment.total: 100},
  {id: 2, source: 'mobile', ms_payment.id: 112, ms_payment.total: 210},
  ...
]

在REST API中返回的预期输出(映射的输出)是:

result = [
  {id: 1, source: 'mobile', ms_payment: { id: 111, total: 100 }},
  {id: 2, source: 'mobile', ms_payment: { id: 112, total: 210 }},
]

有没有使用javascript的有效算法?我目前正在使用Array.map()手动执行此操作,该操作仅返回预期的输出架构,而没有任何循环或方法。

谢谢。

3 个答案:

答案 0 :(得分:2)

您需要迭代条目并获取嵌套对象。

const
    setValue = (object, key, value) => {
        const
            keys = key.split('.'),
            last = keys.pop();
            
        keys.reduce((o, k) => o[k] ??= {}, object)[last] = value;
        return object;
    },
    response = [{ id: 1, source: 'mobile', 'ms_payment.id': 111, 'ms_payment.total': 100 }, { id: 2, source: 'mobile', 'ms_payment.id': 112, 'ms_payment.total': 210 }],
    result = response.map(o => Object
        .entries(o)
        .reduce((r, [k, v]) => setValue(r, k, v), {})
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

您可以使用地图功能。

let response = [
  {id: 1, source: 'mobile', "ms_payment.id": 111, "ms_payment.total": 100},
  {id: 2, source: 'mobile', "ms_payment.id": 112, "ms_payment.total": 210},
];
let newResponse = [];
newResponse = response.map(obj => {
  let newObj = {...obj};
  Object.keys(obj).map(objKey => {
    if (objKey.toString().indexOf(".") >= 0) {
      let nodes = objKey.toString().split(".");
      let parent = nodes[0];
      let child = nodes[1];
      if (newObj.parent) {
        newObj.parent[child] = obj[objKey];
      } else {
        newObj.parent = {};
        newObj.parent[child] = obj[objKey];
      }
      delete newObj[objKey];
    }
  })
  return newObj;
});
console.log(newResponse);

答案 2 :(得分:0)

您可以这样映射数组:

response = [{
    id: 1,
    source: 'mobile',
    'ms_payment.id': 111,
    'ms_payment.total': 100
  },
  {
    id: 2,
    source: 'mobile',
    'ms_payment.id': 112,
    'ms_payment.total': 210
  },
];

const result = response.map((item) => {
  return {
    id: item.id,
    source: item.source,
    ms_payment: {
      id: item['ms_payment.id'],
      total: item['ms_payment.total']
    }
  }
});

console.log(result);