[英]How to add the key with value for each object inside an array of objects?
I have this array of objects and I want to add the value of the object below in the same order as it is inside the items array, Any suggestion?我有这个对象数组,我想在下面添加 object 的值,顺序与它在 items 数组中的顺序相同,有什么建议吗?
const items = [{
tshirt: "Model TS",
jeans: "ModelXW",
},
{
sneakers: "indcdsc54",
furniture: "Table31S"
},
{
dress: "indc54",
short: "shortS2"
},
];
either an object or an array, which one should be easier? object 或数组,哪个更容易?
const obj = [
"localhost:8080.com",
"localhost:3000.com",
"localhost:7000.com",
]
Expected output:预期 output:
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",
},
];
I have tried this way with no success, any suggestion?我试过这种方法没有成功,有什么建议吗?
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)
Like this, assuming the uris are in an array像这样,假设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)
The way I see it your obj
constant should be an array since you don't have any keys in there and assuming that your items
are in the same order this should be enough.在我看来,您的
obj
常量应该是一个数组,因为您在那里没有任何键,并且假设您的items
的顺序相同,这应该足够了。
const newArray = items.map((item,index) => {
item.website = obj[index];
return item
})
Make obj an array使 obj 成为一个数组
const obj = [ "localhost:8080.com", "localhost:3000.com", "localhost:7000.com", ] const items = [{ tshirt: "Model TS", jeans: "ModelXW", }, { sneakers: "indcdsc54", furniture: "Table31S" }, { dress: "indc54", short: "shortS2" }, ]; obj.forEach((item, index) => { if (index < items.length) items[index].website = item; }) console.log(items)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.