簡體   English   中英

在Objects Javascript數組中添加一個Object

[英]Add an Object in an array of Objects Javascript

我需要在數組中添加一個由鍵標識的對象,該數組在course屬性中指定ID。

數組

[{
  "course": 1035, <- The id to find in the objects
  "start_time": "2018-01-04T20:55:00Z",
  "end_time": "2018-01-04T22:00:00Z",
  "details": { <- it has to be created
    <- here the corresponding object according to the id, 
        in this case 1035
  }
 }, {
  "course": 1106,
  "start_time": "2018-01-04T21:00:00Z",
  "end_time": "2018-01-04T22:00:00Z",
}]

對象

{
  "1035": {
    "id": 1035,
    "title": "Some Title1",
    "slug": "live-show",
    "free": true,
    "order": 0,
    "color": "#CB13A1"
  },
  "1106": {
    "id": 1106,
    "title": "Some Title2",
    "slug": "live-show",
    "free": true,
    "order": 0,
    "color": "#CB13A1"
  }
}

預期結果

[{
  "course": 1035,
  "start_time": "2018-01-04T20:55:00Z",
  "end_time": "2018-01-04T22:00:00Z",
  "details": {
    "id": 1035,
    "title": "Some Title1",
    "slug": "live-show",
    "free": true,
    "order": 0,
    "color": "#CB13A1"
  }
 }, {
  "course": 1106,
  "start_time": "2018-01-04T21:00:00Z",
  "end_time": "2018-01-04T22:00:00Z",
  "details": {
    "id": 1106,
    "title": "Some Title2",
    "slug": "live-show",
    "free": true,
    "order": 0,
    "color": "#CB13A1"
  }
}]

 var arr =[{ "course": 1035, "start_time": "2018-01-04T20:55:00Z", "end_time": "2018-01-04T22:00:00Z", "details": { } }, { "course": 1106, "start_time": "2018-01-04T21:00:00Z", "end_time": "2018-01-04T22:00:00Z", }]; var obj = { "1035": { "id": 1035, "title": "Some Title1", "slug": "live-show", "free": true, "order": 0, "color": "#CB13A1" }, "1106": { "id": 1106, "title": "Some Title2", "slug": "live-show", "free": true, "order": 0, "color": "#CB13A1" } }; arr.forEach(item=>{ item.details = obj[item.course]; }); console.log(arr); /*RESULT: [ { "course": 1035, "start_time": "2018-01-04T20:55:00Z", "end_time": "2018-01-04T22:00:00Z", "details": { "id": 1035, "title": "Some Title1", "slug": "live-show", "free": true, "order": 0, "color": "#CB13A1" } }, { "course": 1106, "start_time": "2018-01-04T21:00:00Z", "end_time": "2018-01-04T22:00:00Z", "details": { "id": 1106, "title": "Some Title2", "slug": "live-show", "free": true, "order": 0, "color": "#CB13A1" } } ] */ 

單行而不改變對象/數組(通常是個壞主意)。

target.map(item => Object.assign({}, item, { details: source[item.course]}));

其中target = The Arraysource = The Objects

您可以這樣做:

Object.keys(object).map(key => {
  const obj = object[key]
  // here, you can add all missed keys to your object
  return obj
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM