如何根据需要格式化数组的数组值?

zi8p0yeb  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(261)

我有以下数组,其中包括对象数组。

const arr = [
  [
    {
      "key1": "keyName",
      "key2": "test name1"
    },
    {
      "key1": "keyDescription",
      "key2": "test description1"
    }
  ],
  [
    {
      "key1": "keyName",
      "key2": "test name2"
    },
    {
      "key1": "keyDescription",
      "key2": "test description2"
    }
  ]
]

我要求的结果如下。

result = [
   {
    "key_name": "test name1",
    "key_description": "test description1"
   },
   {
    "key_name": "test name2",
    "key_description": "test description2"
   }
]

我用js'map'和'find'方法尝试过这个,但它给出了错误的格式。

const res = arr.map(i => i.find(j => j.setting_code === "hotelRate")).map(k => k.setting_value)

我听说这可以用“reduce”来实现。如能提出建议,我将不胜感激。谢谢

pieyvz9o

pieyvz9o1#

下面的解决方案仅使用 map 然后是 forEach 在该Map内循环以添加 [key1]: key2 对象对到每个对象。

const arr=[[{key1:"keyName",key2:"test name1"},{key1:"keyDescription",key2:"test description1"}],[{key1:"keyName",key2:"test name2"},{key1:"keyDescription",key2:"test description2"}]];

const result = arr.map(el => {
  const obj = {};
  el.forEach(({key1, key2}) => {
    const snakeKey = key1.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
    obj[snakeKey] = key2;
  })
  return obj;
})

console.log(result);

编辑:正如andreas在评论中指出的,这可以用 reduce 方法(如果需要):

const result = arr.map(el => {
  return el.reduce((result, current) => {
    const snakeKey = current.key1.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
    result[snakeKey] = current.key2;
    return result;
  }, {});
})
des4xlb0

des4xlb02#

arr.map(function(item) {
  var props = {};

  item.forEach(function(keyValue) {
    props[keyValue["key1"]] = keyValue["key2"]; 
  });

  return props;
});

相关问题