JSON到JavaScript中的过滤数组
我有一个JSON字符串:JSON到JavaScript中的过滤数组,javascript,arrays,json,parsing,Javascript,Arrays,Json,Parsing,我有一个JSON字符串: [ { "pk": "alpha", "item": [{ "child": "val" }] }, { "pk": "beta", "attr": "val", "attr2": [ "child1" ] }, { "pk": "alpha", "anotherkey": { "
[
{
"pk": "alpha",
"item": [{
"child": "val"
}]
},
{
"pk": "beta",
"attr": "val",
"attr2": [
"child1"
]
},
{
"pk": "alpha",
"anotherkey": {
"tag": "name"
}
}
]
我需要生成一个没有重复PK的过滤数组,在上面的示例中,最后一个条目:“PK”:“alpha”,“anotherkey”:{
…应该从输出数组中删除。所有这些都使用JavaScript。我尝试了对象JSON.parse,但它返回了许多难以过滤的键、值对,例如“key=2 value”=[对象]“
非常感谢您的帮助。var data=JSON.parse(jsonString);
var data = JSON.parse(jsonString);
var usedPKs = [];
var newData = [];
for (var i = 0; i < data.length; i++) {
if (usedPKs.indexOf(data[i].pk) == -1) {
usedPKs.push(data[i].pk);
newData.push(data[i]);
}
}
// newData will now contain your desired result
var usedPKs=[];
var newData=[];
对于(变量i=0;ivar contents=JSON.parse(“您的JSON字符串”);
var cache={},
结果=[],
内容,主键;
for(变量i=0,len=contents.length;i
//您的示例数据
变量数据存储=[
{
“pk”:“alpha”,
“项目”:[{
“child”:“val”
}]
},
{
“pk”:“beta”,
“attr”:“val”,
“属性2”:[
“儿童1”
]
},
{
“pk”:“alpha”,
“另一个密钥”:{
“标记”:“名称”
}
}
];
//帮助程序,以检查数组是否包含值
Array.prototype.contains=函数(obj){
var i=该长度;
而(我--){
如果(此[i]==obj){
返回true;
}
}
返回false;
}
//临时数组,用于存储针的值(pk值)
var tmp=[];
//存储过滤对象的键的数组。
变量filteredKeys=[];
//遍历您的数据
对于(var i=0;i
处理前必须对其进行解析。然后,您可以遍历数组并将主键添加到集合中。如果您以前见过某个键,请忽略该项。也许您应该使用(!cache.hasownproperty(pk))
而不是(!cache.pk)
非常感谢,非常有帮助,给了我一个想法。现在将其翻译成JScript应该不会太难。
var contents = JSON.parse("your json string");
var cache = {},
results = [],
content, pk;
for(var i = 0, len = contents.length; i < len; i++){
content = contens[i];
pk = content.pk;
if( !cache.hasOwnPropery(pk) ){
results.push(content);
cache[pk] = true;
}
}
// restuls
<script type="text/javascript">
// Your sample data
var dataStore = [
{
"pk": "alpha",
"item": [{
"child": "val"
}]
},
{
"pk": "beta",
"attr": "val",
"attr2": [
"child1"
]
},
{
"pk": "alpha",
"anotherkey": {
"tag": "name"
}
}
];
// Helper to check if an array contains a value
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
// temp array, used to store the values for your needle (the value of pk)
var tmp = [];
// array storing the keys of your filtered objects.
var filteredKeys = [];
// traversing you data
for (var i=0; i < dataStore.length; i++) {
var item = dataStore[i];
// if there is an item with the same pk value, don't do anything and continue the loop
if (tmp.contains(item.pk) === true) {
continue;
}
// add items to both arrays
tmp.push(item.pk);
filteredKeys.push(i);
}
// results in keys 0 and 1
console.log(filteredKeys);
</script>