在 JavaScript/jQuery 中添加到 JSON 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7174633/
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
Adding to JSON array in JavaScript/jQuery
提问by Sharon
I have data being pulled in from various sources, each returning some form of JSON or similar, although, differently formatted each time. I need to get them all into one array, but I can't figure out how to do it.
我有来自各种来源的数据,每个来源都返回某种形式的 JSON 或类似形式,尽管每次都采用不同的格式。我需要将它们全部放入一个数组中,但我不知道该怎么做。
The first set is an array like this:
第一组是这样的数组:
[
Object {id="70", type="ab", dateadded="12345678"},
Object {id="85", type="ab", dateadded="87654321"}, ... more items ...
]
The second set is being pulled in from Facebook, and is like this:
第二组是从 Facebook 拉进来的,是这样的:
[
Object {id="12341234234", created_time="12345678"},
Object {id="567856785678", created_time="87654321"}, ... more items ...
]
So, I need to alter the second set so that it has 'type', and it has 'dateadded' instead of 'created_time', and then I need to get this all into one array so it can be sorted on 'dateadded'.
因此,我需要更改第二组,使其具有“类型”,并且具有“添加日期”而不是“创建时间”,然后我需要将所有这些都放入一个数组中,以便可以按“添加日期”对其进行排序。
How can I do this?
我怎样才能做到这一点?
回答by DavidWainwright
Use the first array's push() method:
使用第一个数组的 push() 方法:
// for each item in second array
firstArray.push(convert(item));
function convert(obj) {
// Convert obj into format compatible with first array and return it
}
Hope this helps.
希望这可以帮助。
回答by mVChr
Assuming you have actual valid JSON instead of what you quoted above:
假设您有实际有效的 JSON 而不是上面引用的内容:
var jsonOld = '[{"id":"70","type":"ab","dateadded":"12345678"},{"id":"85","type":"ab","dateadded":"87654321"}]',
jsonNew = '[{"id":"12341234234","created_time":"12345678"},{"id":"567856785678","created_time":"87654321"}]';
Then first parse these values into actual Javascript arrays:
然后首先将这些值解析为实际的 Javascript 数组:
var mainArr = JSON.parse(jsonOld),
newArr = JSON.parse(jsonNew);
(If you already have actual Javascript arrays instead of JSON strings then skip the above step.)
(如果您已经拥有实际的 Javascript 数组而不是 JSON 字符串,请跳过上述步骤。)
Then just iterate over newArr
and change the properties you need changed:
然后只需迭代newArr
并更改您需要更改的属性:
for (var i = 0, il = newArr.length; i < il; i++) {
newArr[i].type = 'ab';
newArr[i].dateadded = newArr[i].created_time;
delete newArr[i].created_time;
}
And concatenate newArr
into mainArr
:
并连接newArr
成mainArr
:
mainArr = mainArr.concat(newArr);
And sort on dateadded:
并按添加日期排序:
mainArr.sort(function(a, b) { return a.dateadded - b.dateadded; });
This will result in:
这将导致:
[{"id":"70","type":"ab","dateadded":"12345678"},
{"id":"12341234234","type":"ab","dateadded":"12345678"},
{"id":"85","type":"ab","dateadded":"87654321"},
{"id":"567856785678","type":"ab","dateadded":"87654321"}]