简体   繁体   English

通过知道他的ID在JSON中查找对象

[英]Find object in JSON by knowing his id

I have an array of objects, where each object have subobjects with name linkedParts (please see example below), how can I find just that subobject based on subobject ID? 我有一个对象数组,其中每个对象都有名称为linkedParts子对象(请参见下面的示例),如何才能基于子对象ID找到该子对象?

I already used something similar to find object by object ID and code looks like: 我已经使用类似的方法通过对象ID查找对象,并且代码如下所示:

var updatedPart = axCalculation.selectedParts.filter(function( obj ) {
    return obj.id === response.data.id;
})[0];

However I am not sure if I can search just knowing subobjects. 但是我不确定是否可以搜索仅知道子对象。 If yes how? 如果是,怎么办? axCalculation.selectedParts looksLike: axCalculation.selectedParts看起来像:

[{
    "id": "1fccb481-53a0-400e-8831-80acd1793bee",
    "euroCode": "7812BGSHABW",
    "position": "REAR",
    "category": "REAR_WINDOW",
    "glassPartType": "GLASS",
    "description": "TODO: DECODE 7812BGSHABW",
    "calculatedPrice": 15768.00,
    "operation": "REPLACE",
    "selectionSource": "MANUAL",
    "linkedParts": []
}, {
    "id": "71e1dc3b-47a2-4406-970a-ef0911c93396",
    "euroCode": "7812AGSHMVZ",
    "position": "FRONT",
    "category": "FRONT_WINDOW",
    "glassPartType": "GLASS",
    "description": "TODO: DECODE 7812AGSHMVZ",
    "descriptionByUser": "TEST DESCC",
    "calculatedPrice": 5749.50,
    "priceByUser": 574.22,
    "operation": "REPLACE",
    "selectionSource": "MANUAL",
    "linkedParts": [{
        "id": "0f45cd6b-7053-4625-8ec9-87281c126e1d",
        "partNumber": "LSD",
        "description": "LEPÍCÍ SADA",
        "calculatedPrice": 562.50,
        "selectionSource": "AUTOMATIC",
        "enabled": true
    }, {
        "id": "61bbbdad-1838-4327-8c38-8808a35a403c",
        "partNumber": "string",
        "description": "GEL POD SENZOR",
        "calculatedPrice": 87.48,
        "selectionSource": "AUTOMATIC",
        "enabled": true
    }]
}]

You can have simple search combining filter and some . 您可以结合filtersome简单的搜索。 This does however make the assumption you want to search a sub-array of objects. 但是,这确实假设您要搜索对象的子数组。

let find = (prop, by, where) => {
  return data.filter(d =>
    d[prop].some(sub => sub[by] === where)
  );
}

usage 用法

console.log(find('linkedParts', 'id', '0f45cd6b-7053-4625-8ec9-87281c126e1d'));

Obviously ive made it overly configurable where you pass every property in but if you do not need this you can hard code things. 显然,IVE使它在传递每个属性的地方都过于可配置,但是如果不需要此属性,则可以对事物进行硬编码。

fiddle EDIT: Forgot to mention the fiddle uses ES6 syntax which i believe IE doesn't currently support. 小提琴编辑:忘了提琴使用ES6语法,我相信IE当前不支持。

some docs 一些文档

filter docs 筛选器文件

If you want to get the objects that contains a "linkedPart" of a defined id : 如果要获取包含已定义id的“ linkedPart”的对象:

var linkedPartId = "0f45cd6b-7053-4625-8ec9-87281c126e1d";

var objBasedOnLinkedPart = axCalculation.selectedParts.filter(function( obj ) {
    for (linkedPart in obj.linkedParts) {
        if (linkedPart.id === linkedPartId) {
            return true;
        }
    }
})[0];

You can use reduce to flatten the array, and then use filter to find the matching result: 您可以使用reduce来使数组变平,然后使用filter来找到匹配的结果:

function find(ary, subId) {
  return ary.reduce(function(prev, cur) {
    return prev.concat(cur.linkedParts);
  }, []).filter(function(item) { 
    return item.id == subId 
  })[0];
}

Array.reduce will take all the linkedParts arrays and put them into one array. Array.reduce将采用所有linkedParts数组并将它们放入一个数组。 Array.filter will return all matches that would match the passed value. Array.filter将返回所有与传递的值匹配的匹配项。

jsFiddle jsFiddle

The above was an es5 implementation, it's a lot prettier in es6: 上面是es5的实现,在es6中更漂亮:

function find(ary, subId) {
  return ary.reduce((p,c) => p.concat(c.linkedParts), []).filter(i => i.id == subId)[0];
}

The only answer I saw which return effectively the linkedPart object is the reduce/filter one, but when I change the desired id for an invalid one, I still get something. 我看到的唯一可以有效返回linkedPart对象的答案是reduce / filter一个,但是当我为一个无效的对象更改所需的id时,仍然可以得到。 So here the version I would use. 所以这里是我要使用的版本。

EDIT : I added a proof that changing the found object is changing the initial one 编辑:我添加了一个证明,更改找到的对象正在更改初始对象

 var selectedParts = [{ "id": "1fccb481-53a0-400e-8831-80acd1793bee", "euroCode": "7812BGSHABW", "position": "REAR", "category": "REAR_WINDOW", "glassPartType": "GLASS", "description": "TODO: DECODE 7812BGSHABW", "calculatedPrice": 15768.00, "operation": "REPLACE", "selectionSource": "MANUAL", "linkedParts": [] }, { "id": "71e1dc3b-47a2-4406-970a-ef0911c93396", "euroCode": "7812AGSHMVZ", "position": "FRONT", "category": "FRONT_WINDOW", "glassPartType": "GLASS", "description": "TODO: DECODE 7812AGSHMVZ", "descriptionByUser": "TEST DESCC", "calculatedPrice": 5749.50, "priceByUser": 574.22, "operation": "REPLACE", "selectionSource": "MANUAL", "linkedParts": [{ "id": "0f45cd6b-7053-4625-8ec9-87281c126e1d", "partNumber": "LSD", "description": "LEPÍCÍ SADA", "calculatedPrice": 562.50, "selectionSource": "AUTOMATIC", "enabled": true }, { "id": "61bbbdad-1838-4327-8c38-8808a35a403c", "partNumber": "string", "description": "GEL POD SENZOR", "calculatedPrice": 87.48, "selectionSource": "AUTOMATIC", "enabled": true }] }]; //Search for the desired object(s) var wantedId = "0f45cd6b-7053-4625-8ec9-87281c126e1d"; var linkedParts = []; selectedParts.forEach(function(obj) { var foundLinkedParts = obj.linkedParts.filter(function(subObj) { return subObj.id == wantedId; }); linkedParts = linkedParts.concat(foundLinkedParts); }); console.log(linkedParts); //Modify something in found object linkedParts[0].partNumber = "My part number"; console.log(linkedParts[0].partNumber); //Verify in object where initially stored console.log(selectedParts[1]["linkedParts"][0].partNumber); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM