jQuery 如何在 JSON 对象中存储数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15365589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:54:26  来源:igfitidea点击:

How to store data in JSON object

jqueryjson

提问by Jagd

I have data with the following structure:

我有以下结构的数据:

Unique ID (int) | First Name (string) | Last Name (string) | Pct (double)

唯一 ID (int) | 名字(字符串)| 姓氏(字符串)| Pct(双)

A set of the data might look something like this:

一组数据可能如下所示:

1 | John | Hancock | 49.5
2 | John | Hancock | 95.0
3 | Jane | Hancock | 89.5
4 | Jane | Hancock | 73.5
5 | Jane | Hancock | 96.5
6 | Fred | Flintstone | 45.8

1 | 约翰 | 汉考克 | 49.5
2 | 约翰 | 汉考克 | 95.0
3 | 简| 汉考克 | 89.5
4 | 简| 汉考克 | 73.5
5 | 简| 汉考克 | 96.5
6 | 弗雷德 | 打火石 | 45.8

What I need is to store this data on the client-side so that it is accessible to the browser and can be manipulated using jQuery.

我需要的是将这些数据存储在客户端,以便浏览器可以访问它并可以使用 jQuery 进行操作。

For example, I have a dropdown (select) on the page that has three values in it:

例如,我在页面上有一个下拉列表(选择),其中包含三个值:

1) Low Percentile
2) Mid Percentile
3) High Percentile

1) 低百分位
2) 中百分位
3) 高百分位

When the user selects one of the values in the dropdown then I need to be able to select items from my data above that qualify for the selected value. For example, if they select the Low Percentile value then I need to retrieve all of the items from the data that have a percentage less than 60%.

当用户选择下拉列表中的值之一时,我需要能够从上面的数据中选择符合所选值的项目。例如,如果他们选择 Low Percentile 值,那么我需要从数据中检索百分比小于 60% 的所有项目。

I'm fairly versatile with jQuery, but I've never used it to store anything of this sort for client-side retrieval. Can I somehow store this data in JSON objects on the client-side, which in turn can be selected from and manipulated at will?

我对 jQuery 相当多才多艺,但我从来没有用它来存储这种类型的任何东西以供客户端检索。我可以以某种方式将这些数据存储在客户端的 JSON 对象中,然后可以随意选择和操作吗?

采纳答案by Leeish

So basically:

所以基本上:

var javascriptObject = $.parseJSON(jsonString);

var jsonString = JSON.stringify(javascriptObject);

JavaScript is much like any other OOP.

JavaScript 很像任何其他 OOP。

var foo = {}; //NEW Object
foo.bar = 1;
foo.bars = 2;
foo.bar.date = 3;
var jsonString = JSON.stringify(foo);
//jsonString is now a "JSON Object" that holds the data found in object foo.
console.log(jsonString); //To see what it looks like.

However if all of this is for client side usage, just stick with JavaScript objects. No need to convert them to JSON. JSON objects are really for sending data to other sources as they are strings. Usually used in AJAX requests.

然而,如果所有这些都是为了客户端使用,那么就坚持使用 JavaScript 对象。无需将它们转换为 JSON。JSON 对象实际上是用于将数据发送到其他来源,因为它们是字符串。通常用于 AJAX 请求。

EDIT BASED ON COMMENT

根据评论编辑

$(document).ready(function(){
    var globalObject = {};
    globalObject.foo = 1;
    globalObject.bar = 2;

    $(el).change(function(){
        globalObject.foo = $(this).val();
    });
});

回答by bozdoz

JSON stands for Javascript Object Notation. If you're familiar with Objects, you should be able to work with it.

JSON 代表 Javascript 对象表示法。如果您熟悉对象,您应该能够使用它。

For your example, I would probably save the variable as an Array of objects (because it is numbered first). Hopefully you wouldn't mind reassigning the numbers to zero-based increments (0, 1, 2...).

对于您的示例,我可能会将变量保存为对象数组(因为它首先编号)。希望您不介意将数字重新分配为从零开始的增量(0、1、2...)。

Perhaps you could do something like this instead, if you want to save it client-side:

如果你想在客户端保存它,也许你可以做这样的事情:

var data = [
{ fname : "John", lname : "Hancock", value : 49.5 },
{ fname : "John", lname : "Hancock", value : 95.0 }
];

That's just the first two as an example. You could then iterate over the array with a for loop for(var i=0, count = data.length; i < count; i++), and do something with the data if data[i].value < 60.

这只是前两个示例。然后,您可以使用 for 循环遍历数组for(var i=0, count = data.length; i < count; i++),并对数据执行某些操作 if data[i].value < 60

jQuery's got a nice function called .each()that you could just as easily use too. Also, you could have the JSON saved in a .json file and called by jQuery.getJSON(), if you have a need for that. Both could be good starts in learning about this.

jQuery 有一个很好的函数,叫做.each(),你也可以很容易地使用它。此外,如果需要,您可以将 JSON 保存在.json文件中并由jQuery.getJSON()调用。两者都可能是了解这一点的良好开端。

回答by danludwig

While I'm not proud of this answer, it would probably work for your needs. It also does not require a browser to have HTML5 local storage.

虽然我对这个答案并不感到自豪,但它可能会满足您的需求。它也不需要浏览器来拥有 HTML5 本地存储。

<input type="hidden" id="json_data" />

<script type="text/javascript>
    var theData = [
        {
            id: 1,
            firstName: 'John',
            lastName: 'Hancock',
            pct: 49.5
        },
        // other objects
        {
            id: 6,
            firstName: 'Fred',
            lastName: 'Flintstone',
            pct: 45.8
        }
    ];
    var dataAsJsonString = JSON.stringify(theData);
    $('#json_data').val(dataAsJsonString); // store data in hidden field

    // later on...
    var getDataBackOut = $.parseJSON($('#json_data').val());
    // you can now iterate over the array to find what you need
</script>

回答by Tim Lieberman

var foo = localStorage.getItem("bar");
// ...
localStorage.setItem("bar", foo);

Use HTML5 Local storage

使用 HTML5 本地存储