遍历数组并将元素推送到对象

时间:2019-05-29 09:50:01

标签: javascript typescript

我有一个看起来像这样的数组对象

identificationType: "DL",
identificationDesc: "Test",
referenceNumber: "123456789",
country: "US",
province: "Illinois"

我希望我的数据模型看起来像这样

identificationType: "DL",
identificationDesc: "Test",
referenceNumber: "123456789",
issuedEntity:{
country: "US",
province: "Illinois"
}

最初,我将对象数组分配给变量

identification: this.model['identificationArray'].

IdentificationArray是一个Object数组,包含所有详细信息,但采用简单的json格式。我希望能够以某种方式操纵它,并通过创建一个IssuedEntity对象,然后在该对象内部的国家和省的详细信息来插入数据。

为此,我尝试遍历数组,但出现错误。有人可以帮我弄清楚该怎么做。

myModel.identification.forEach(identificationObj => {
issuedEntity: {
province = identificationObj.issuedEntity.province,
country = identificationObj.issuedEntity.country,
}
} 
);

4 个答案:

答案 0 :(得分:3)

您可以使用数组映射功能并使用必需的键返回对象

let data = [{
  identificationType: "DL",
  identificationDesc: "Test",
  referenceNumber: "123456789",
  country: "US",
  province: "Illinois"
}]

let newData = data.map(function(item) {
  return {
    identificationType: item.identificationType,
    identificationDesc: item.identificationDesc,
    referenceNumber: item.referenceNumber,
    issuedEntity: {
      country: item.country,
      province: item.province
    }

  }
});

console.log(newData)

答案 1 :(得分:3)

即使您可能想使用 ES6语法,您也可以这样做:

let data = [{
  identificationType: "DL",
  identificationDesc: "Test",
  referenceNumber: "123456789",
  country: "US",
  province: "Illinois"
}]

let newData = data.map(({
  identificationType,
  identificationDesc,
  referenceNumber,
  country,
  province
}) => ({
  identificationType,
  identificationDesc,
  referenceNumber,
  issuedEntity: {
    country,
    province
  }
}));

console.log(newData)

答案 2 :(得分:1)

您可以map覆盖原始对象,并更改其内部值或为其添加外部值。

myModel.identification.map(idObj => {
   idObj.issuedEntity = {
       province: idObj.province
       country: idObj.country
   }
   delete idObj.province
   delete idObj.country
   return idObj
})

答案 3 :(得分:0)

我认为这里存在问题,在为对象分配值时,我们使用=而不是:冒号。

    myModel.identification.forEach(identificationObj => {
    issuedEntity: {
        province **=** identificationObj.issuedEntity.province,
        country **=** identificationObj.issuedEntity.country,
    }
});

应该是这样

myModel.identification.forEach(identificationObj => {
    issuedEntity: {
        province: identificationObj.issuedEntity.province,
        country: identificationObj.issuedEntity.country,
    }
});