首页 > 解决方案 > 如何为对象数组中的每个对象添加带有值的键?

问题描述

我有这个对象数组,我想以与 items 数组中相同的顺序添加下面对象的值,有什么建议吗?

const items = [{
    tshirt: "Model TS",
    jeans: "ModelXW",
  },
  {
    sneakers: "indcdsc54",
    furniture: "Table31S"
  },
  {
    dress: "indc54",
    short: "shortS2"
  },
];

对象或数组,哪个更容易?

const obj = [
  "localhost:8080.com",
  "localhost:3000.com",
  "localhost:7000.com",
]

预期输出:

const items = [{
    tshirt: "Model TS",
    jeans: "ModelXW",
    website: "localhost:8080.com",
  },
  {
    sneakers: "indcdsc54",
    furniture: "Table31S",
    website: "localhost:3000.com",
  },
  {
    dress: "indc54",
    short: "shortS2",
    website: "localhost:7000.com",
  },
];

我试过这种方法没有成功,有什么建议吗?

const items = [{
    tshirt: "Model TS",
    jeans: "ModelXW"
  },
  {
    sneakers: "indcdsc54",
    furniture: "Table31S"
  },
  {
    dress: "indc54",
    short: "shortS2"
  }
];

const obj = [
  "localhost:8080.com",
  "localhost:3000.com",
  "localhost:7000.com",
]

let newArray = obj.map(uri => items.map(i => i["website"] = uri ))

console.log(newArray)

标签: javascriptalgorithm

解决方案


像这样,假设uris在一个数组中

const items = [{
    tshirt: "Model TS",
    jeans: "ModelXW"
  },
  {
    sneakers: "indcdsc54",
    furniture: "Table31S"
  },
  {
    dress: "indc54",
    short: "shortS2"
  }
];

const uris = [
  "localhost:8080.com",
  "localhost:3000.com",
  "localhost:7000.com",
]

let newArray = items.map((item,i) => (item.website = uris[i], item)); 
// OR          items.map((item,i) => ({website : uris[i], ...item}));
console.log(newArray)


推荐阅读