我如何提取某些对象并在JavaScript中动态生成它们?

问题描述 投票:-1回答:2

社区,

我是JavaScript的初学者。我有一个JSON文件,并且数组中有多个对象。如何提取某些对象并用JavaScript动态生成它们?

JSON文件就是这样:

data:[{"artist": "Jason Mraz", "album": "XYZ", "Year":"2012", "Quote":"I'll be there", "image": "mraz.jpg"},
{"artist": "Ed Sheeran", "album": "Divide", "Year":"2018", "Quote":"Let's Go", "image": "sheeran.jpg"},
{"artist": "Kahlid", "album": "ABC", "Year":"2014", "Quote":"Let me Go", "image": "khalid.jpg"}
{"artist": "Taylor Swift", "album": "123", "Year":"2013", "Quote":"Im generous", "image": "swift.jpg"}, 
{"artist": "Harry Styles", "album": "TAE", "Year":"2017", "Quote":"I'll be the King of UK", "image": "styles.jpg"},
{"artist": "Maroon 5", "album": "Memories", "Year":"2019", "Quote":"Let us in the car", "image": "maroon.jpg"},
]

我只想提取“艺术家”,“专辑”和“图像”,然后用Javascript动态生成它们。

我的建议是一个循环。

我该怎么做,或者我该怎么写?

而且我如何在div内放置一个段落?像那样,但是用Javascript。

<div class="container>
  <p class="artist"> Jason Mraz </p>
</div>

我得到了div。但是我该如何在Div内放置一个段落?

    var div = document.createElement("div");
    var attr = document.createAttribute("class");
    attr.value="container";
    div.setAttributeNode(attr);
    document.body.appendChild(div);

感谢您的建议。

TheBeas1。

javascript arrays json list dom
2个回答
0
投票

只需使用map从对象数组中获得所需的属性:

const result = data.map(({artist, album, image}) => ({artist, album, image}));

示例:

let data = [
    { "artist": "Jason Mraz", "album": "XYZ", "Year": "2012", "Quote": "I'll be there", "image": "mraz.jpg" },
    { "artist": "Ed Sheeran", "album": "Divide", "Year": "2018", "Quote": "Let's Go", "image": "sheeran.jpg" },
    { "artist": "Kahlid", "album": "ABC", "Year": "2014", "Quote": "Let me Go", "image": "khalid.jpg" },
    { "artist": "Taylor Swift", "album": "123", "Year": "2013", "Quote": "Im generous", "image": "swift.jpg" },
    { "artist": "Harry Styles", "album": "TAE", "Year": "2017", "Quote": "I'll be the King of UK", "image": "styles.jpg" },
    { "artist": "Maroon 5", "album": "Memories", "Year": "2019", "Quote": "Let us in the car", "image": "maroon.jpg" },
]

const result = data.map(({artist, album, image}) => ({artist, album, image}));
console.log(result);

0
投票

我只想提取“艺术家”,“专辑”和“图像”

通过传递回调提供的函数作为参数来使用map方法。

var data = [{"artist": "Jason Mraz", "album": "XYZ", "Year":"2012", "Quote":"I'll be there", "image": "mraz.jpg"}, {"artist": "Ed Sheeran", "album": "Divide", "Year":"2018", "Quote":"Let's Go", "image": "sheeran.jpg"}, {"artist": "Kahlid", "album": "ABC", "Year":"2014", "Quote":"Let me Go", "image": "khalid.jpg"}, {"artist": "Taylor Swift", "album": "123", "Year":"2013", "Quote":"Im generous", "image": "swift.jpg"}, {"artist": "Harry Styles", "album": "TAE", "Year":"2017", "Quote":"I'll be the King of UK", "image": "styles.jpg"}, {"artist": "Maroon 5", "album": "Memories", "Year":"2019", "Quote":"Let us in the car", "image": "maroon.jpg"}]

console.log(data.map(({artist, album, image}) => ({artist, album, image})));
© www.soinside.com 2019 - 2024. All rights reserved.