如果子数组具有动态键值对对象,则在javascript中展平数组对象

时间:2018-04-23 04:31:50

标签: javascript typescript

如何获得此数组的平面数组对象?我想将所有键值从子数组对象移动到其父对象:

[
  {
    "Attributes": [
      {
        "Name": "profile",
        "Value": "UI"
      },
      {
        "Name": "phone_number",
        "Value": "+91123456789"
      },
      {
        "Name": "email",
        "Value": "to_test@test.in"
      }
    ],
    "UserCreateDate": 1524465619.163,
    "Username": "neeraj"
  }
]

必需的JSON:

[
  {
    "UserCreateDate": 1524465619.163,
    "Username": "neeraj",
    "profile": "UI",
    "phone_number": "+91123456789",
    "email": "to_test@test.in"
  }
]

2 个答案:

答案 0 :(得分:1)

您可以使用遍历对象的键/值迭代的递归函数来展平:

const input = {
  "PaginationToken": "string",
  "Users": [{
    "Attributes": [{
      "Name": "string",
      "Value": "string"
    }],
    "Enabled": 'boolean',
    "MFAOptions": [{
      "AttributeName": "string",
      "DeliveryMedium": "string"
    }],
    "UserCreateDate": 'number',
    "UserLastModifiedDate": 'number',
    "Username": "string",
    "UserStatus": "string"
  }]
};
const getKeyValsFromObj = (obj) => Object.entries(obj)
  .reduce((accum, [key, value]) => {
    if (Array.isArray(value)) {
      value.forEach(innerObj => accum = [...accum, ...getKeyValsFromObj(innerObj)]);
    } else accum.push([key, value]);
    return accum;
  }, []);
const keysVals = getKeyValsFromObj(input);
const finalObj = keysVals.reduce((obj, [key, val]) => {
  obj[key] = val;
  return obj;
}, {});
console.log(finalObj);

答案 1 :(得分:1)

您可以使用Total count of Distinct_Cell_ID's, Total count of Distinct_Gene_ID's, Total sum of count in Table 1. 遍历数组,然后使用array#map遍历array#map并使用Attributes创建一个包含所有键的对象Object.assign键值格式的对象并返回此对象。

Attributes