简体   繁体   中英

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

I have two JSON objects and I want to combine them into one JSON object. Also, I want them to be added as sublevels in the 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'
}

Desired 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'
  }
}

How can I do this?

You can add your two objects into an array, and then use .map() to map each object to an array of the form [object.Title, object] . Using this new array, you can use Object.fromEntries() to convert it to an object. By putting your objects into an array, you can extend this for multiple movie objects:

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

As a side note, there is no such thing as a JSON object .

You could use dynamic property name ( computed property name )

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

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