简体   繁体   中英

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?

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)

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)

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
})

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM