Reputation: 677
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?
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?
const obj = [
"localhost:8080.com",
"localhost:3000.com",
"localhost:7000.com",
]
Expected 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)
Upvotes: 0
Views: 52
Reputation: 372
Make obj an array
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)
Upvotes: 1
Reputation: 158
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.
const newArray = items.map((item,index) => {
item.website = obj[index];
return item
})
Upvotes: 1
Reputation: 177691
Like this, assuming the uris are in an array
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)
Upvotes: 3