在 JavaScript 中查找 JSON [英] JSON find in JavaScript

查看:50
本文介绍了在 JavaScript 中查找 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了在 JSON 中查找数据之外,还有更好的方法吗?用于编辑和删除.

for(var k in objJsonResp) {如果(objJsonResp[k].txtId == id){如果(动作=='删除'){objJsonResp.splice(k,1);} 别的 {objJsonResp[k] = newVal;}休息;}}

数据按地图列表排列.喜欢:

<预><代码>[{id:value, pId:value, cId:value,...},{id:value, pId:value, cId:value,...},...]

解决方案

(您不是通过JSON"进行搜索,而是通过数组进行搜索——JSON 字符串已经反序列化为对象图,在这种情况下是一个数组.)

一些选项:

使用对象代替数组

如果你能控制这个东西的生成,它是否必须是一个数组?因为如果没有,还有一个更简单的方法.

说这是你的原始数据:

<预><代码>[{"id": "one", "pId": "foo1", "cId": "bar1"},{"id": "two", "pId": "foo2", "cId": "bar2"},{id":三",pId":foo3",cId":bar3"}]

您可以改为执行以下操作吗?

<代码>{一个":{pId":foo1",cId":bar1"},二":{pId":foo2",cId":bar2"},三":{pId":foo3",cId":bar3"}}

然后通过 ID 查找相关条目是微不足道的:

id = "one";//管他呢var entry = objJsonResp[id];

...更新中:

objJsonResp[id] =/* 新值 */;

...并删除它:

删除objJsonResp[id];

这利用了这样一个事实,即在 JavaScript 中,您可以使用属性名称作为字符串索引到对象中——并且该字符串可以是文字,也可以来自变量,如 id 以上.

放入一个 ID 到索引的映射

(愚蠢的想法,早于上述.由于历史原因而保留.)

看起来你需要把它作为一个数组,在这种情况下,没有比搜索数组更好的方法,除非你想在它上面放一张地图,如果你可以控制对象的生成.例如,假设你原来有这个:

<预><代码>[{"id": "one", "pId": "foo1", "cId": "bar1"},{"id": "two", "pId": "foo2", "cId": "bar2"},{id":三",pId":foo3",cId":bar3"}]

生成代码可以提供一个 id-to-index 映射:

<代码>{指数": {一":0,二":1,三":2},数据": [{"id": "one", "pId": "foo1", "cId": "bar1"},{"id": "two", "pId": "foo2", "cId": "bar2"},{id":三",pId":foo3",cId":bar3"}]}

然后在变量 id 中获取 id 的条目是微不足道的:

var index = objJsonResp.index[id];var obj = objJsonResp.data[index];

这利用了您可以使用属性名称索引到对象的事实.

当然,如果这样做,则在修改数组时必须更新映射,这可能会成为维护问题.

但是如果您无法控制对象的生成,或者更新 ids-to-indexes 的映射是代码过多和/或维护问题,那么您将不得不进行蛮力搜索.

蛮力搜索(更正)

有点过时(尽管您确实询问是否有更好的方法:-)),但是您循环遍历数组的代码不正确.详情在这里,但你不能使用for..in 循环遍历数组索引(或者更确切地说,如果你这样做,你必须特别注意这样做);for..in 遍历对象的属性,而不是数组的索引.使用非稀疏数组(而你的数组是非稀疏数组)的最佳选择是标准的老式循环:

var k;for (k = 0; k 

var k;for (k = someArray.length - 1; k >= 0; --k) {/* ... */}

无论你喜欢哪个(后者在所有实现中并不总是更快,这对我来说是违反直觉的,但我们就是这样).(对于 sparse 数组,您可能会使用 for..in 但又要特别注意避免陷阱;更多内容请参见上面链接的文章.)

在数组上使用 for..in 似乎 在简单的情况下可以工作,因为数组的每个索引都有属性,并且只有其他默认属性(length 及其方法)被标记为不可枚举.但是一旦您在数组对象上设置(或框架设置)任何其他属性(这是完全有效的;数组只是对 length 属性进行了一些特殊处理的对象),它就会中断.

Is there a better way other than looping to find data in JSON? It's for edit and delete.

for(var k in objJsonResp) {
  if (objJsonResp[k].txtId == id) {
    if (action == 'delete') {
      objJsonResp.splice(k,1);
    } else {
      objJsonResp[k] = newVal;
    }
    break;
  }
}

The data is arranged as list of maps. Like:

[
  {id:value, pId:value, cId:value,...},
  {id:value, pId:value, cId:value,...},
  ...
]

解决方案

(You're not searching through "JSON", you're searching through an array -- the JSON string has already been deserialized into an object graph, in this case an array.)

Some options:

Use an Object Instead of an Array

If you're in control of the generation of this thing, does it have to be an array? Because if not, there's a much simpler way.

Say this is your original data:

[
    {"id": "one",   "pId": "foo1", "cId": "bar1"},
    {"id": "two",   "pId": "foo2", "cId": "bar2"},
    {"id": "three", "pId": "foo3", "cId": "bar3"}
]

Could you do the following instead?

{
    "one":   {"pId": "foo1", "cId": "bar1"},
    "two":   {"pId": "foo2", "cId": "bar2"},
    "three": {"pId": "foo3", "cId": "bar3"}
}

Then finding the relevant entry by ID is trivial:

id = "one"; // Or whatever
var entry = objJsonResp[id];

...as is updating it:

objJsonResp[id] = /* New value */;

...and removing it:

delete objJsonResp[id];

This takes advantage of the fact that in JavaScript, you can index into an object using a property name as a string -- and that string can be a literal, or it can come from a variable as with id above.

Putting in an ID-to-Index Map

(Dumb idea, predates the above. Kept for historical reasons.)

It looks like you need this to be an array, in which case there isn't really a better way than searching through the array unless you want to put a map on it, which you could do if you have control of the generation of the object. E.g., say you have this originally:

[
    {"id": "one",   "pId": "foo1", "cId": "bar1"},
    {"id": "two",   "pId": "foo2", "cId": "bar2"},
    {"id": "three", "pId": "foo3", "cId": "bar3"}
]

The generating code could provide an id-to-index map:

{
    "index": {
        "one": 0, "two": 1, "three": 2
    },
    "data": [
        {"id": "one",   "pId": "foo1", "cId": "bar1"},
        {"id": "two",   "pId": "foo2", "cId": "bar2"},
        {"id": "three", "pId": "foo3", "cId": "bar3"}
    ]
}

Then getting an entry for the id in the variable id is trivial:

var index = objJsonResp.index[id];
var obj = objJsonResp.data[index];

This takes advantage of the fact you can index into objects using property names.

Of course, if you do that, you have to update the map when you modify the array, which could become a maintenance problem.

But if you're not in control of the generation of the object, or updating the map of ids-to-indexes is too much code and/ora maintenance issue, then you'll have to do a brute force search.

Brute Force Search (corrected)

Somewhat OT (although you did ask if there was a better way :-) ), but your code for looping through an array is incorrect. Details here, but you can't use for..in to loop through array indexes (or rather, if you do, you have to take special pains to do so); for..in loops through the properties of an object, not the indexes of an array. Your best bet with a non-sparse array (and yours is non-sparse) is a standard old-fashioned loop:

var k;
for (k = 0; k < someArray.length; ++k) { /* ... */ }

or

var k;
for (k = someArray.length - 1; k >= 0; --k) { /* ... */ }

Whichever you prefer (the latter is not always faster in all implementations, which is counter-intuitive to me, but there we are). (With a sparse array, you might use for..in but again taking special pains to avoid pitfalls; more in the article linked above.)

Using for..in on an array seems to work in simple cases because arrays have properties for each of their indexes, and their only other default properties (length and their methods) are marked as non-enumerable. But it breaks as soon as you set (or a framework sets) any other properties on the array object (which is perfectly valid; arrays are just objects with a bit of special handling around the length property).

这篇关于在 JavaScript 中查找 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆