簡體   English   中英

JavaScript中的JSON數據如何動態添加新級別?

[英]How can I dynamically add a new level to JSON data in JavaScript?

我有兩個 JSON 對象,我想將它們組合成一個 JSON object。此外,我希望將它們作為子級別添加到 output JSON object 中。

JSON Object 1 :

{ 
  Title: '7500',
  Year: '2019',
  Rated: 'R',
  Released: '18 Jun 2020',
  Runtime: '93 min',
  Genre: 'Action, Drama, Thriller'
}

JSON Object 2 :

{
  Title: 'Deadpool',
  Year: '2016',
  Rated: 'R',
  Released: '12 Feb 2016',
  Runtime: '108 min',
  Genre: 'Action, Adventure, Comedy, Sci-Fi'
}

期望 Output

responses: {
  7500: {
    Title: '7500',
    Year: '2019',
    Rated: 'R',
    Released: '18 Jun 2020',
    Runtime: '93 min',
    Genre: 'Action, Drama, Thriller'
  },
  Deadpool: {
    Title: 'Deadpool',
    Year: '2016',
    Rated: 'R',
    Released: '12 Feb 2016',
    Runtime: '108 min',
    Genre: 'Action, Adventure, Comedy, Sci-Fi'
  }
}

我怎樣才能做到這一點?

您可以將兩個對象添加到一個數組中,然后使用.map()到 map 每個 object 到[object.Title, object]形式的數組。 使用這個新數組,您可以使用Object.fromEntries()將其轉換為 object。通過將對象放入數組中,您可以將其擴展為多個電影對象:

 const movies = [{ Title: '7500', Year: '2019', Rated: 'R', Released: '18 Jun 2020', Runtime: '93 min', Genre: 'Action, Drama, Thriller' }, { Title: 'Deadpool', Year: '2016', Rated: 'R', Released: '12 Feb 2016', Runtime: '108 min', Genre: 'Action, Adventure, Comedy, Sci-Fi' }]; const result = Object.fromEntries(movies.map(obj => [obj.Title, obj])); console.log(result);

作為旁注, 沒有 JSON object 這樣的東西

您可以使用動態屬性名稱( 計算屬性名稱

 const obj1 = { Title: "7500", Year: "2019", Rated: "R", Released: "18 Jun 2020", Runtime: "93 min", Genre: "Action, Drama, Thriller", }; const obj2 = { Title: "Deadpool", Year: "2016", Rated: "R", Released: "12 Feb 2016", Runtime: "108 min", Genre: "Action, Adventure, Comedy, Sci-Fi", }; const obj = { [obj1.Title]: obj1, [obj2.Title]: obj2, }; console.log(obj);

暫無
暫無

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

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