创建具有相同键和值的新对象

时间:2021-03-02 17:29:38

标签: javascript reactjs

我正在尝试创建一个新对象,并在其中插入来自“旧”对象的某些值,我已经尝试这样做了一段时间,但每次我都在同一个位置。

[
{ initials: "HLC", name: "HAPAG", color: "#FF8040" }
​
{ initials: "HMM", name: "HYUNDAI", color: "#C10D11" }
​
{ initials: "MSC", name: "MSC", color: "#F5BA07" }
​
{ initials: "ONE", name: "ONE", color: "#A80F89" }
]

这将是我从 API 获取的对象(它在数组内部),我需要创建一个只有特定值的新对象,如下所示:

const newObj = {
initials: "HLC",
initials: "HMM",
initials: "MSC",
initials: "ONE",
}

不知何故,我总是以 newObj = {initials: "ONE"} 结束,我认为这是因为我正在使用循环来做到这一点。 我需要用其他两个键做同样的事情,但如果我知道如何用一个键来做,我会很好。

2 个答案:

答案 0 :(得分:2)

您可以将 destructured 字段作为 shorthand property names 映射到新对象。

const original = [
  { initials: "HLC" , name: "HAPAG"   , color: "#FF8040" },
  { initials: "HMM" , name: "HYUNDAI" , color: "#C10D11" },
  { initials: "MSC" , name: "MSC"     , color: "#F5BA07" },
  { initials: "ONE" , name: "ONE"     , color: "#A80F89" }
];

const modified = original.map(({ initials }) => ({ initials }));

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

如果你想要所有的首字母,你可以类似地映射它们:

const original = [
  { initials: "HLC" , name: "HAPAG"   , color: "#FF8040" },
  { initials: "HMM" , name: "HYUNDAI" , color: "#C10D11" },
  { initials: "MSC" , name: "MSC"     , color: "#F5BA07" },
  { initials: "ONE" , name: "ONE"     , color: "#A80F89" }
];

const modified = {
  initials: original.map(({ initials }) => initials)
};

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

答案 1 :(得分:1)

创建一个对象

const newObj = {
  initiales: "HLC",
  initiales: "HMM",
  initiales: "MSC",
  initiales: "ONE",
}

相当于

const newObj = {}
newObj.initiales = "HLC" 
newObj.initiales = "HMM" 
newObj.initiales = "MSC" 
newObj.initiales = "ONE" 

最后你有:

const newObj = { initiales: "ONE" }