JSON 到 JavaScript 中过滤的数组
JSON to filtered Array in JavaScript
我有这个JSON字符串:
[
{
"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=[object Object]"
。
任何帮助将不胜感激。
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 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>
相关文章:
- 使用一个键的值数组过滤多个javascript对象
- 根据另一个包含角度 js 中对象的数组过滤包含对象的数组
- Javascript:按字符串数组过滤对象数组
- 在 javascript 中使用数组过滤 for AngularJS
- 挖空和选择器的数组过滤问题
- Lodash 按数组的属性数组过滤
- 如何用另一个字符串数组过滤ng重复中的字符串数组
- 如何根据javascript数组过滤rss数据
- 基于NodeJS中的其他数组过滤/搜索对象的JavaScript数组
- 使用不带嵌套循环的数组过滤对象数组js
- 使用数组过滤数组Javascript
- 用一维数组过滤多维数组
- AngularJS:如何给值数组过滤
- Angularjs,逐个数组过滤
- 用另一个对象数组过滤Javascript对象数组
- 创建搜索栏以将数组过滤到表中
- 通过id数组过滤角度数据
- coffeescript -数组过滤不工作
- Backbone.js:如何通过模型ID数组过滤对象集合
- 使用基于嵌套值的数组过滤对象数组