gpt4 book ai didi

javascript - 循环对象数组并创建一个新对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:39:38 25 4
gpt4 key购买 nike

我有一个对象数组,每个对象都有一个标题、内容和 contentHTML。我想映射这个数组并创建一个新对象。新对象将采用 title 属性的值,并将其用作每个 content 和 contentHTML 属性的父属性。下面的代码似乎只是获取数组中的最后一个对象。

结果是:

{
"sidebar": {
"text": "Some sidbar text here",
"content": "<p>Some sidebar text here</p>"
}
}

预期结果是:

{
header: {
text: "Some header text here",
content: "<p>Some header text here</p>"
},
footer: {
text: "Some footer text here",
content: "<p>Some footer text here</p>"
},
sidebar: {
text: "Some sidbar text here",
content: "<p>Some sidebar text here</p>"
}
}

var originalObj = [{
title: "header",
content: "Some header text here",
contentHTML: "<p>Some header text here</p>"
},
{
title: "footer",
content: "Some footer text here",
contentHTML: "<p>Some footer text here</p>"
},
{
title: "sidebar",
content: "Some sidbar text here",
contentHTML: "<p>Some sidebar text here</p>"
}
];
let newObject = {};
for (let item of originalObj) {
var tempObj = {
[item.title]: {
text: item.content,
content: item.contentHTML
}
};
newObject = tempObj;
}
console.log(newObject);

最佳答案

每次你做的时候你都在用新的值覆盖你的对象

var tempObj = {//object keys}

使用扩展运算符复制以前的值。扩展运算符循环遍历对象的可迭代值并扩展它们。

var originalObj = [
{
title: "header",
content: "Some header text here",
contentHTML: "<p>Some header text here</p>"
},
{
title: "footer",
content: "Some footer text here",
contentHTML: "<p>Some footer text here</p>"
},
{
title: "sidebar",
content: "Some sidbar text here",
contentHTML: "<p>Some sidebar text here</p>"
}
];

let newObject = {};
for (let item of originalObj) {
newObject = {
...newObject,
[item.title]: {
text: item.content,
content: item.contentHTML
}
};
}
console.log(newObject);

关于javascript - 循环对象数组并创建一个新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51539788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com