如何根据需要格式化数组数组的值?
How to format values of the arrays of array as required?
我有以下包含对象数组的数组。
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' 来完成。我将不胜感激。谢谢!
以下解决方案仅使用 map
,然后在该映射内使用 forEach
循环将 [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);
编辑:正如安德烈亚斯在评论中指出的那样,如果需要,这个 可以 用 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;
}, {});
})
arr.map(function(item) {
var props = {};
item.forEach(function(keyValue) {
props[keyValue["key1"]] = keyValue["key2"];
});
return props;
});
我有以下包含对象数组的数组。
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' 来完成。我将不胜感激。谢谢!
以下解决方案仅使用 map
,然后在该映射内使用 forEach
循环将 [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);
编辑:正如安德烈亚斯在评论中指出的那样,如果需要,这个 可以 用 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;
}, {});
})
arr.map(function(item) {
var props = {};
item.forEach(function(keyValue) {
props[keyValue["key1"]] = keyValue["key2"];
});
return props;
});