【问题标题】:How to set javascript variables to json array elements?如何将javascript变量设置为json数组元素?
【发布时间】:2018-04-02 22:16:39
【问题描述】:

这是我下面的 Javascript 代码示例。我写这篇文章的主要原因是我有一个关于最后一个函数的问题,即我的 GalleryImage 函数。该函数中有四个字符串变量。在每个变量中,我应该将对应键中的一个元素存储在我的 JSON 文件的数组中。我怎么做?我的 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"
        }

  ]
}

【问题讨论】:

  • @Biffen 我编辑了它
  • JSON 是一种符号格式。如果您执行var images = [,您将拥有一个 JS 对象。我想这就是你真正的意思。请创建minimal reproducible example 解释输入和预期输出
  • @mplungjan 从那个 var images 代码开始是我的 JSON 文件,所以它是 JSON 代码。我只需要了解如何将图像数组中的每个键放入我编写的 Javascript 函数中的变量中。变量将是字符串。
  • 作为“JSON 码”没用 你会得到一个 JS 对象或者你需要使用 JSON.parse 使字符串成为一个 JS 对象。

标签: javascript html css json


【解决方案1】:

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

element.variable

例子:

mJson.description

希望我的回答对你有帮助!

【讨论】:

  • 好的。谢谢!
  • 这是否首先访问密钥?我知道你正在访问元素,但我们不是必须先访问密钥吗?
  • element.variableelement["variable"] 一样,所以你在调用element.variable时是在调用key
  • 我们是否必须将其解析为字符串?
  • 你的回答是如何被讨厌的,我认为你的回答是对的。
【解决方案2】:

你可以试试这个:

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

另一种选择是尝试使用类来实现,但概念基本相同。

【讨论】:

    猜你喜欢
    • 2019-01-07
    • 2019-03-07
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 2016-11-18
    相关资源
    最近更新 更多