简体   繁体   中英

How can I extract exactly 2 keys and values from several objects in an array

I have this json-file

artist:[
{artist: "Henry", Year :"XYZ", album: "ABC", image: "image.jpg"}
{artist: "Lisa", Year :"1998", album: "All the time", image: "image.jpg"}
{artist: "David", Year :"2001", album: "Lets go", image: "image.jpg"}
{artist: "James", Year :"1997", album: "Memories", image: "image.jpg"}
{artist: "Julia", Year :"2002", album: "Technology", image: "image.jpg"}
{artist: "Bob", Year :"1995", album: "Chill 5", image: "image.jpg"}
{artist: "Frank", Year :"1996", album: "DeadRat", image: "image.jpg"}
]

I want to extract artist, album and image and dynamically put it on the website. How can i do that?

you can do it this way:

 const artist=[ {artist: "Henry", Year :"XYZ", album: "ABC", image: "image.jpg"}, {artist: "Lisa", Year :"1998", album: "All the time", image: "image.jpg"}, {artist: "David", Year :"2001", album: "Lets go", image: "image.jpg"}, {artist: "James", Year :"1997", album: "Memories", image: "image.jpg"}, {artist: "Julia", Year :"2002", album: "Technology", image: "image.jpg"}, {artist: "Bob", Year :"1995", album: "Chill 5", image: "image.jpg"}, {artist: "Frank", Year :"1996", album: "DeadRat", image: "image.jpg"} ] var arr = artist.map(x=>{return {artist:x.artist,album:x.album,image:x.image}}) console.log(arr)

})

in order to show your data on the React application, you can follow this Code

function App() {
  const artist = [
    { artist: "Henry", Year: "XYZ", album: "ABC", image: "image.jpg" },
    { artist: "Lisa", Year: "1998", album: "All the time", image: "image.jpg" },
    { artist: "David", Year: "2001", album: "Lets go", image: "image.jpg" },
    { artist: "James", Year: "1997", album: "Memories", image: "image.jpg" },
    { artist: "Julia", Year: "2002", album: "Technology", image: "image.jpg" },
    { artist: "Bob", Year: "1995", album: "Chill 5", image: "image.jpg" },
    { artist: "Frank", Year: "1996", album: "DeadRat", image: "image.jpg" }
  ];
  var arr = artist.map(x => {
    return { artist: x.artist, album: x.album, image: x.image };
  });
  return (
    <div className="App">
      {arr.map(x => {
        return (
          <div>
            {x.album} : {x.artist}
            <img alt="" src={x.src} />
          </div>
        );
      })}
    </div>
  );
}

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