如何将javascript变量设置为json数组元素?

时间:2018-04-02 14:00:07

标签: javascript html css json

以下是我的Javascript代码示例。我写这篇文章的主要原因是因为我对最后一个函数有疑问,这是我的GalleryImage函数。该函数中有四个字符串变量。在每个变量中,我应该在我的JSON文件的数组中存储来自correspoding键的元素。我怎么做?我的javascript代码下面是我的JSON文件代码示例。

function GalleryImage(mJSON) {

    var locate = "";
    var description = "";
    var date = "";
    var url = "";
    //implement me as an object to hold the following data about an image:
    //1. location where photo was taken
    //2. description of photo
    //3. the date when the photo was taken
    //4. either a String (src URL) or an an HTMLImageObject (bitmap of the photo. https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement)
}
"images": [
        {
            "imgPath": "img/places/australia.jpg",
            "imgLocation": "Australia",
            "description": "Loch Ard Gorge",
            "date": "01/01/2016"
        },
        {
            "imgPath": "img/places/austria.jpg",
            "imgLocation": "Austria",
            "description": "Austrian chapel",
            "date": "01/02/2016"
        }

  ]
}

2 个答案:

答案 0 :(得分:-1)

您可以像在字典中一样访问JS对象数组中的变量:

element.variable

示例:

mJson.description

我希望我的回答很有帮助!

答案 1 :(得分:-1)

你可以尝试这个:



debugger;
const images = [
        {
            "imgPath": "img/places/australia.jpg",
            "imgLocation": "Australia",
            "description": "Loch Ard Gorge",
            "date": "01/01/2016"
        },
        {
            "imgPath": "img/places/austria.jpg",
            "imgLocation": "Austria",
            "description": "Austrian chapel",
            "date": "01/02/2016"
        }
];

const GalleryImage = (props) => {
    return {
     locate : props.imgLocation,
     description :  props.description,
     date :  props.date,
     url :  props.imgPath ? props.imgPath : props.imgPath // Here is where you need to check if is a string or use the default bitmap
    };
}

const imagesParsed = images.map(props => GalleryImage(props));




另一个选择是尝试用类来做,但基本上是相同的概念。