映射到REACTJS中的Obejct Javascript转换

时间:2018-11-07 10:33:35

标签: arrays reactjs dictionary

我想在REACTJS中将以下Map转换为Object 我该如何实现

[
      {
        "lastName": "Last name should have atleast 1 characters "
      },
      {
        "role": "may not be null"
      },
      {
        "name": "Name should have atleast 1 characters "
      }
    ]

转换为

{
  "lastName": "Last name should have atleast 1 characters ",
  "role": "may not be null",
  "name": "Name should have atleast 1 characters "
}

3 个答案:

答案 0 :(得分:1)

Array.prototype.reduce()可用于从数组创建对象。

请参见下面的实际示例。

// Input.
const input = [{lastName: 'Last name should have atleast 1 characters'}, {role: 'may not be null'}, {name: 'Name should have atleast 1 characters '}]

// Convert Array To Object.
const convertArrayToObject = array => array.reduce((acc, x) => {
  for (const key in x) acc[key] = x[key]
  return acc
}, {})

// Output + Proof.
const output = convertArrayToObject(input)
console.log(output)

答案 1 :(得分:0)

您需要缩小数组以将其形状更改为所需的对象

const a = [
  {
    "lastName": "Last name should have atleast 1 characters "
  },
  {
    "role": "may not be null"
  },
  {
    "name": "Name should have atleast 1 characters "
  }
];

const b = a.reduce((acc, item) => {
  const key = Object.keys(item)[0];
  return {
    ...acc,
    [key]: item[key],
  };
}, []);

console.log(b);

答案 2 :(得分:0)

您可以使用嵌套的reduce,但是如果阵列中的键不是唯一的,则阵列中较早的键将被以后的键覆盖:

console.log(
  [
    {
      lastName:
        'Last name should have atleast 1 characters ',
    },
    {
      role: 'may not be null',
    },
    {
      name: 'Name should have atleast 1 characters ',
    },
  ].reduce((mainResult, item) =>
    Object.entries(item).reduce(
      (result, [key, value]) => (
        (result[key] = value), result
      ),
      mainResult,
    ),
    {}
  ),
);

看到您的答案(应该添加注释而不是添加答案),看起来您的数组是JSON字符串数组,请尝试以下操作:

console.log(
  //array of json strings
  [
    '{"lastName":"Last name should have atleast 1 characters "}',
    '{"role":"may not be null"}',
    '{"name":"Name should have atleast 1 characters "}',
  ]
    .map((item) => JSON.parse(item))
    .reduce((mainResult, item) =>
      Object.entries(item).reduce(
        (result, [key, value]) => (
          (result[key] = value), result
        ),
        mainResult,
      ),
      {}
    ),
);