javascript - 如何为对象数组中的每个对象添加带有值的键?
问题描述
我有这个对象数组,我想以与 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)
解决方案
像这样,假设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)
推荐阅读
- pandas - 转置数据框后的列名
- flow-project - 没有为 Aimsun/Flow-project 找到模块 Flow
- html - ie/safari 和 chrome 上的标题显示不同。如何让它一样
- r - R Markdown 中的大字体
- google-cloud-platform - 如何使用谷歌云文本到语音 API?我联系了他们的支持并没有太大帮助。任何聪明的人可以让我度过这个难关吗?
- loops - 如何在循环中导航低谷范围和填充范围?
- python - Windows 上的 Python 64 位:OSError: [WinError 193] %1 is geen geldige Win32-toepassing
- processing - 处理中静止物体的自适应背景减法
- vue.js - Vue Axios - 使用 bootstrapVue 和 vuex,上传文件和文本仍有问题?
- javascript - 如何使用正则表达式对不同的字母(不一定是连续的)进行分组