繁体   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