问题描述
**js 替换,将
数组他替换成对象
[
{
name: "aaa"
sqlVal: 134
},
{
name: "vvv"
sqlVal: 567
}
]
{
aaa: 134,
vvv:567
}
如何替换?
**
**js 替换,将
数组他替换成对象
[
{
name: "aaa"
sqlVal: 134
},
{
name: "vvv"
sqlVal: 567
}
]
{
aaa: 134,
vvv:567
}
如何替换?
**
let array = [
{
name: "aaa",
sqlVal: 134
},
{
name: "vvv",
sqlVal: 567
}
]
let map = new Map()
array.forEach(item => {
map.set(item.name, item.sqlVal)
})
let obj = Object.fromEntries(map)
console.log(obj)
var arr = [
{
name: "aaa",
sqlVal: 134
},
{
name: "vvv",
sqlVal: 567
}
]
function getObj(arr) {
var obj = {}
arr.forEach(item => {
obj[item.name] = item.sqlVal
})
return obj
}
console.log(getObj(arr))
const arr = [
{ name: "aaa", sqlVal: 134 },
{ name: "vvv", sqlVal: 567 }
];
const obj = arr.reduce((acc, curr) => {
acc[curr.name] = curr.sqlVal;
return acc;
}, {});
console.log(obj); // { aaa: 134, vvv: 567 }
首先,我们定义一个空对象作为reduce()方法的初始值。然后,使用reduce()方法遍历数组中的每个元素,并将每个元素的name属性作为对象的键,将sqlVal属性作为对象的值,最终返回一个新的对象。
const arr = [
{ name: "aaa", sqlVal: 134 },
{ name: "vvv", sqlVal: 567 }
]
const result = arr.reduce((prev, curr) => {
prev[curr.name] = curr.sqlVal
return prev
}, {})
console.log(result);
const arr = [
{ name: "aaa", sqlVal: 134 },
{ name: "vvv", sqlVal: 567 }
];
const obj = Object.fromEntries(arr.map(({ name, sqlVal }) => [name, sqlVal]));
console.log(obj);
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决