循环遍历对象数组并创建一个新对象。

3
我有一个对象数组,每个对象都有标题、内容和contentHTML。我想映射此数组并创建一个新对象。新的对象将取得标题属性的值,并将其用作每个内容和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);

6个回答

3

每次执行时,您都在用新值覆盖对象

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);


谢谢你,请问...tempObj是做什么的? - user3486427
将现有的tempObj解压到新的tempObj中 - 基本上允许您扩展对象。尽管个人而言,我会做类似于 newObject[item.title] = {text:item.content, content:item.contentHTML}; 的事情。 - Niet the Dark Absol
tempObj是冗余的。您可以通过将tempObj替换为newObject(位于varsplat旁边),然后您也不需要newObject = tempObj;来获得相同的结果。 - James

1
这个替代方案使用函数reduce来构建所需的输出。

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>" }],
    newObject = originalObj.reduce((a, {title, content: text, contentHTML: content} = obj) => {
      return Object.assign(a, {[title]: {text, content}});
    }, Object.create(null));

console.log(newObject);
.as-console-wrapper { max-height: 100% !important; top: 0; }


1
你曾经用 tempObj 的内容覆盖了 newObject,如果直接像这样写入 newObject 会更容易些。请保留html标签。

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[item.title] = {
    text: item.content,
    content: item.contentHTML
  }
}
console.log(newObject);

我希望这有意义。


1
您也可以使用 Array#reduce 来实现类似的功能:

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>"
 }
];

var output = originalObj.reduce((accumulator, ele) => {
  accumulator[ele['title']] = {'text': ele['content'], 'content': ele['contentHTML']}
  return accumulator;
}, {})

console.log(output);


0

这个问题已经得到了回答,但如果还有帮助:

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

0

I tried with a different example and wanted to answer more dynamically firstly, getting how many unique values we can have for a property i.e,res array in this example then, filtering the objects and pushing into an array that the object's property matches with each unique value of the res array in the example the resultant object is resObj

let anArray = [{id: 1, name:"orange"},
{id: 2, name:"orange"},
{id: 3, name:"apple"},
{id: 4, name:"apple"},
{id: 5, name:"rusk"},
{id: 6, name:"grape"}]
let res =  [...new Set(anArray.map(item => item.name))];
let resObj = {};

let newObj = (item, arr) => {
    let resArr = [];
  
    anArray.map((obj) => {
     if(item == obj.name){
     resArr.push(obj)
     }
 })
 return resArr
}
resObject = Object.fromEntries(res.map((item) => [item, newObj(item, anArray) ]) )

 
console.log(resObject)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接