如何两个对象之间的匹配值,并创造新的具有特定值 [英] How to match values between two objects and create new with specific values

查看:165
本文介绍了如何两个对象之间的匹配值,并创造新的具有特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象的数组 oDataSet aProperties 对象,我想匹配的相同是在 aPropertis 和和在 oDataSet 和创造价值在 aSelectedDataSet 这在开始是一个空对象

它是如何建议做这件事的JS / jQuery的

注:不应该有任何的硬codeD 属性中环/解决方案做了比赛
该aProperties是包含这个值,但也可以是变化的(当然应该有匹配的ODATA对象...)

有关澄清以下为示例对象是如何建立

http://jsfiddle.net/4rh6​​tt25/5/

这是输入

  //这是给定对象的数组,它可以有很多,在这里我把只有两个实例的阵列中进行演示的目的
变种oDataSet = [{
    __metadata:{
        AAA:111,
        BBB:222
    },
    to_ExcludedTerms:{结果:[]},
    to_ListTypeGroupAssignment:{
        结果:
            {
                AuthorisationGroup:'AuthorisationGroup 1',
                ListTypeGroup:ListTypeGroup1',
                ListTypeGroupDesc​​ription:'ListTypeGroupDesc​​ription 1',
                ParentKey:8ae25d47-c3cc-4ee3-A040-ea00505692111',
                __metadata:{}
            },
            {
                AuthorisationGroup:'AuthorisationGroup 2',
                ListTypeGroup:ListTypeGroup2',
                ListTypeGroupDesc​​ription:'ListTypeGroupDesc​​ription 2',
                ParentKey:34bcdc74-ab42-4538-8657-0a2b0473fcb7',
                __metadata:{}
            },
            {
                AuthorisationGroup:'AuthorisationGroup 3',
                ListTypeGroup:ListTypeGroup3',
                ListTypeGroupDesc​​ription:'ListTypeGroupDesc​​ription 3',
                ParentKey:34bcdc74-ab42-4538-8657-0a2b0473fcb5',
                __metadata:{}
            }
        ]
    }
},{
    //这是用相同的键,但不同的值的对象的第二个实例
    __metadata:{
        AAA:333,
        BBB:444
    },
    to_ExcludedTerms:{结果:[]},
    to_ListTypeGroupAssignment:{
        结果:
            {
                AuthorisationGroup:AuthorisationGroup 6',
                ListTypeGroup:ListTypeGroup6',
                ListTypeGroupDesc​​ription:ListTypeGroupDesc​​ription 6',
                ParentKey:8ae25d47-c3cc-4ee3-A040-ea00505692116',
                __metadata:{}
            },
            {
                AuthorisationGroup:'AuthorisationGroup 7',
                ListTypeGroup:ListTypeGroup7',
                ListTypeGroupDesc​​ription:'ListTypeGroupDesc​​ription 7'​​,
                ParentKey:34bcdc74-ab42-4538-8657-0a2b0473fcb7',
                __metadata:{}
            },
            {
                AuthorisationGroup:'AuthorisationGroup 8',
                ListTypeGroup:ListTypeGroup8',
                ListTypeGroupDesc​​ription:'ListTypeGroupDesc​​ription 8',
                ParentKey:34bcdc74-ab42-4538-8657-0a2b0473fcb8',
                __metadata:{}
            }
        ]
    }
}
];//这是价值观,我要搜索发现oDataSet
//相同的结构下的to_ListTypeGroupAssignment或其他财产
//应符合以下路径,但根据其结果是唯一的
//硬codeD属性
VAR aProperties = [
    to_ListTypeGroupAssignment / ListTypeGroup
    to_ListTypeGroupAssignment / ListTypeGroupDesc​​ription
]

这是输出

这是例子的输出应该在输入两个对象的合并来建立上述

  VAR aSelectedDataSet = [
    {
        __metadata:{
            AAA:111,
            BBB:222
        },
        to_ListTypeGroupAssignment:{
            结果:
                {
                    ListTypeGroup:ListTypeGroup1',
                    ListTypeGroupDesc​​ription:ListTypeGroupDesc​​ription 1'
                },
                {
                    ListTypeGroup:ListTypeGroup2',
                    ListTypeGroupDesc​​ription:'ListTypeGroupDesc​​ription 2',                },
                {
                    ListTypeGroup:ListTypeGroup3',
                    ListTypeGroupDesc​​ription:'ListTypeGroupDesc​​ription 3',
                }
            ]
        }
    },
    {
        __metadata:{
            AAA:333,
            BBB:444
        },
        to_ListTypeGroupAssignment:{
            结果:
                {
                    ListTypeGroup:ListTypeGroup1',
                    ListTypeGroupDesc​​ription:ListTypeGroupDesc​​ription 1'
                },
                {
                    ListTypeGroup:ListTypeGroup2',
                    ListTypeGroupDesc​​ription:'ListTypeGroupDesc​​ription 2',                },
                {
                    ListTypeGroup:ListTypeGroup3',
                    ListTypeGroupDesc​​ription:'ListTypeGroupDesc​​ription 3',
                }
            ]
        }
    }]

刚刚从下面的评论澄清:)
这可硬件codeD 的唯一一件事就是结果
不会任何财产名称,如ListTypeGroup&安培; ListTypeGroupDesc​​ription
这应该是的通用并从aProperties读

你看的OData结构应该像下面

 属性(比如 - > to_ListTypeGroupAssignmen)
        结果(硬coded和放大器;必须在每一个存在的对象)
             属性(比如ListTypeGroup&放大器; ListTypeGroupDesc​​ription与存在价值)

如果我需要更清楚,请让我知道如何,这更多的信息,我要补充...这是在我更新的问题,尽可能...


解决方案

您可以使用此递归,纯JavaScript函数:

下面的代码片段应用此功能,您提供的样本数据,并返回所需的结果:

\r
\r

函数extract(数据,选择curpath){\r
    VAR的结果= {};\r
    //已遍历来获得数据路径的部分:\r
    curpath = curpath || '';\r
    如果(typeof运算数据!=='对象'){//数据是原始的(我们假设)\r
        返回的数据;\r
    }\r
    如果(typeof运算data.slice ==='功能'){//数据是一个数组\r
        返回Data.Map中(功能(EL,IDX){\r
            返回提取物(EL,选择curpath); //相同的路径!\r
        });\r
    }\r
    //数据是一个对象:\r
    //了__metadata财产的具体情况\r
    如果(数据.__元==不确定和放大器;!&安培; curpath.length === 0){\r
        结果.__元=数据.__元数据;\r
    }\r
    //这个算法的核心:只需要相关的路径...\r
    VAR子查询= select.filter(功能(路径){\r
        返回(路径+'/')的indexOf(curpath)== 0。\r
    });\r
    subselect.forEach(功能(路径,_,子查询){\r
        //然后得到这样的路径的一个属性...\r
        VAR道具= path.substr(curpath.length).split('/')[0];\r
        //和检查,如果我们有当前对象的该属性:\r
        如果(数据[道具]!==未定义){\r
            //如果是这样,递归同时加入这对当前路径:\r
            结果[道具] =提取物(数据[道具],子查询,curpath +道具+'/');\r
        }\r
    });\r
    //结果的具体案例财产\r
    如果(data.results!==未定义){//用递归相同的路径!\r
        result.results =提取物(data.results,选择curpath);\r
    }\r
    返回结果;\r
}\r
\r
\r
//测试数据\r
变种oDataSet = [{\r
    __metadata:{\r
        AAA:111,\r
        BBB:222\r
    },\r
    to_ExcludedTerms:{结果:[]},\r
    to_ListTypeGroupAssignment:{\r
        结果:\r
            {\r
                AuthorisationGroup:'AuthorisationGroup 1',\r
                ListTypeGroup:ListTypeGroup1',\r
                ListTypeGroupDesc​​ription:'ListTypeGroupDesc​​ription 1',\r
                ParentKey:8ae25d47-c3cc-4ee3-A040-ea00505692111',\r
                __metadata:{}\r
            },\r
            {\r
                AuthorisationGroup:'AuthorisationGroup 2',\r
                ListTypeGroup:ListTypeGroup2',\r
                ListTypeGroupDesc​​ription:'ListTypeGroupDesc​​ription 2',\r
                ParentKey:34bcdc74-ab42-4538-8657-0a2b0473fcb7',\r
                __metadata:{}\r
            },\r
            {\r
                AuthorisationGroup:'AuthorisationGroup 3',\r
                ListTypeGroup:ListTypeGroup3',\r
                ListTypeGroupDesc​​ription:'ListTypeGroupDesc​​ription 3',\r
                ParentKey:34bcdc74-ab42-4538-8657-0a2b0473fcb5',\r
                __metadata:{}\r
            }\r
        ]\r
    }\r
},{\r
    __metadata:{\r
        AAA:333,\r
        BBB:444\r
    },\r
    to_ExcludedTerms:{结果:[]},\r
    to_ListTypeGroupAssignment:{\r
        结果:\r
            {\r
                AuthorisationGroup:AuthorisationGroup 6',\r
                ListTypeGroup:ListTypeGroup6',\r
                ListTypeGroupDesc​​ription:ListTypeGroupDesc​​ription 6',\r
                ParentKey:8ae25d47-c3cc-4ee3-A040-ea00505692116',\r
                __metadata:{}\r
            },\r
            {\r
                AuthorisationGroup:'AuthorisationGroup 7',\r
                ListTypeGroup:ListTypeGroup7',\r
                ListTypeGroupDesc​​ription:'ListTypeGroupDesc​​ription 7'​​,\r
                ParentKey:34bcdc74-ab42-4538-8657-0a2b0473fcb7',\r
                __metadata:{}\r
            },\r
            {\r
                AuthorisationGroup:'AuthorisationGroup 8',\r
                ListTypeGroup:ListTypeGroup8',\r
                ListTypeGroupDesc​​ription:'ListTypeGroupDesc​​ription 8',\r
                ParentKey:34bcdc74-ab42-4538-8657-0a2b0473fcb8',\r
                __metadata:{}\r
            }\r
        ]\r
    }\r
}\r
];\r
\r
VAR aProperties = [\r
    to_ListTypeGroupAssignment / ListTypeGroup\r
    to_ListTypeGroupAssignment / ListTypeGroupDesc​​ription\r
];\r
//(样本数据完)\r
\r
//调用函数得到的结果:\r
VAR aSelectedDataSet =提取物(oDataSet,aProperties);\r
\r
//因为只有这个片段:输出结果可读格式\r
的document.write('< pre>'+ JSON.stringify(aSelectedDataSet,0,4)+'< / pre>');

\r

\r
\r

该算法的说明:

在code被注释掉。这是算法如何工作的:


  • 的功能是递归的并采取的当前数据,这将是原始数据的只是一个分部,一旦函数递归调用。

  • 的功能也将路径-style属性来选择。另外这个列表将会缩短为函数的递归调用,所以它只有那些仍然适用于数据部分的条目。

  • 第三个参数是一个已经走过的路径。在初始呼叫这只是空字符串,但随着递归踢,它将成为to_ListTypeGroupAssignment /',后来甚至to_ListTypeGroupAssignment / ListTypeGroup /'(总是以终止斜杠)。

  • 函数的每次调用将返回的(路径式)选择符合给定数据的一部分。

  • 的功能开始通过识别数据的类型:无论是原始值(字符串,号码,布尔值),或阵列(它是在初始呼叫的情况),或者一个(非阵列)对象。

  • 如果它是一个数组,该函数只称为递归每个元素不添加任何的路径。然后每个呼叫的结果被存储在数组中,成为返回值。

  • 如果它是一个原始值,这意味着我们递归在树一叶。既然我们来到这里,我们可以假设路径是相匹配,直到这点,因此必须返回原始值,以便它可以被添加到结果

  • 它是一个对象,则选择路径遍历,以查看是否在这些路径下一级与当前数据的一个对象的属性相匹配。如果是这样,该属性值是通过递归调用传递,同时还加入了那块路径,以当前路径

有明显的例外__这是在code分开处理元数据结果

I've array of objects oDataSet and aProperties object and I want to match the identical values that are found in aPropertis and and In oDataSet and create the aSelectedDataSet which in beginning is an empty object

How it's recommend to do it in JS/Jquery

Note: there shouldnt be any hardcoded property in the loops/solution to do the match the aProperties is contain this value but it can be change (and of course there should be match in the oData object...)

For clarification Following is example how the objects is built

http://jsfiddle.net/4rh6tt25/5/

This is the input

 //This is given array of object which can be many ,here I put just two instance in the array for demonstration purpose
var oDataSet = [{
    __metadata: {
        aaa: 111,
        bbb: 222
    },
    to_ExcludedTerms: {results: []},
    to_ListTypeGroupAssignment: {
        results: [
            {
                AuthorisationGroup: 'AuthorisationGroup 1',
                ListTypeGroup: 'ListTypeGroup1',
                ListTypeGroupDescription: 'ListTypeGroupDescription 1',
                ParentKey: '8ae25d47-c3cc-4ee3-a040-ea00505692111',
                __metadata: {}
            },
            {
                AuthorisationGroup: 'AuthorisationGroup 2',
                ListTypeGroup: 'ListTypeGroup2',
                ListTypeGroupDescription: 'ListTypeGroupDescription 2',
                ParentKey: '34bcdc74-ab42-4538-8657-0a2b0473fcb7',
                __metadata: {}
            },
            {
                AuthorisationGroup: 'AuthorisationGroup 3',
                ListTypeGroup: 'ListTypeGroup3',
                ListTypeGroupDescription: 'ListTypeGroupDescription 3',
                ParentKey: '34bcdc74-ab42-4538-8657-0a2b0473fcb5',
                __metadata: {}
            }
        ]
    }
}, {
    //This is the second instance of the object with same keys but different values
    __metadata: {
        aaa: 333,
        bbb: 444
    },
    to_ExcludedTerms: {results: []},
    to_ListTypeGroupAssignment: {
        results: [
            {
                AuthorisationGroup: 'AuthorisationGroup 6',
                ListTypeGroup: 'ListTypeGroup6',
                ListTypeGroupDescription: 'ListTypeGroupDescription 6',
                ParentKey: '8ae25d47-c3cc-4ee3-a040-ea00505692116',
                __metadata: {}
            },
            {
                AuthorisationGroup: 'AuthorisationGroup 7',
                ListTypeGroup: 'ListTypeGroup7',
                ListTypeGroupDescription: 'ListTypeGroupDescription 7',
                ParentKey: '34bcdc74-ab42-4538-8657-0a2b0473fcb7',
                __metadata: {}
            },
            {
                AuthorisationGroup: 'AuthorisationGroup 8',
                ListTypeGroup: 'ListTypeGroup8',
                ListTypeGroupDescription: 'ListTypeGroupDescription 8',
                ParentKey: '34bcdc74-ab42-4538-8657-0a2b0473fcb8',
                __metadata: {}
            }
        ]
    }
}
];

//This is the values which I should search find in oDataSet
//The to_ListTypeGroupAssignment or other property which under the same structure
//should be with the following path but under the results which is the only
//hardcoded property
var aProperties = [
    "to_ListTypeGroupAssignment/ListTypeGroup",
    "to_ListTypeGroupAssignment/ListTypeGroupDescription"
]

This is the output

This is example of the output which should be build from the merge of both objects in the input above

var aSelectedDataSet = [
    {
        __metadata: {
            aaa: 111,
            bbb: 222
        },
        to_ListTypeGroupAssignment: {
            results: [
                {
                    ListTypeGroup: 'ListTypeGroup1',
                    ListTypeGroupDescription: 'ListTypeGroupDescription 1'
                },
                {
                    ListTypeGroup: 'ListTypeGroup2',
                    ListTypeGroupDescription: 'ListTypeGroupDescription 2',

                },
                {
                    ListTypeGroup: 'ListTypeGroup3',
                    ListTypeGroupDescription: 'ListTypeGroupDescription 3',
                }
            ]
        }
    },
    {
        __metadata: {
            aaa: 333,
            bbb: 444
        },
        to_ListTypeGroupAssignment: {
            results: [
                {
                    ListTypeGroup: 'ListTypeGroup1',
                    ListTypeGroupDescription: 'ListTypeGroupDescription 1'
                },
                {
                    ListTypeGroup: 'ListTypeGroup2',
                    ListTypeGroupDescription: 'ListTypeGroupDescription 2',

                },
                {
                    ListTypeGroup: 'ListTypeGroup3',
                    ListTypeGroupDescription: 'ListTypeGroupDescription 3',
                }
            ]
        }
    }

]

just to clarify from the comments below :) The only thing that can be hard-coded is the results. Not any property name like ListTypeGroup& ListTypeGroupDescription This should be generic and read from aProperties

The structure of you look at the oData should be like following

property(like -> to_ListTypeGroupAssignmen)
        results(hardcoded & mandatory in every exist object)
             properties(like ListTypeGroup& ListTypeGroupDescription with there values)

If I need to make it more clear please let me know How,which additional info I should add...This is after I update the question as much as possible...

解决方案

You could use this recursive, pure JavaScript function:

The snippet below applies this function to the example data you provided and returns the required result:

function extract(data, select, curpath) {
    var result = {};
    // Part of the path that has been traversed to get to data:
    curpath = curpath || '';        
    if (typeof data !== 'object') { // data is a primitive (we assume)
        return data;
    } 
    if (typeof data.slice === 'function') { // data is an Array
        return data.map(function (el, idx) {
            return extract(el, select, curpath); // same path!
        });
    }
    // data is an Object:
    // The specific case of the "__metadata" property
    if (data.__metadata !== undefined && curpath.length === 0) {
        result.__metadata = data.__metadata;
    }
    // Core of this algorithm: take the relevant paths only...
    var subselect = select.filter(function(path) {
        return (path+'/').indexOf(curpath) == 0;
    });
    subselect.forEach(function (path, _, subselect) {
        // then get the next property in such path...
        var prop = path.substr(curpath.length).split('/')[0];
        // and check if we have that property on the current object:
        if (data[prop] !== undefined) {
            // If so, recurse while adding this to the current path:
            result[prop] = extract(data[prop], subselect, curpath+prop+'/');
        }
    });
    // The specific case of the "results" property
    if (data.results !== undefined) {  // recurse with same path!
        result.results = extract(data.results, select, curpath);
    }
    return result;
} 


// Test data
var oDataSet = [{
    __metadata: {
        aaa: 111,
        bbb: 222
    },
    to_ExcludedTerms: {results: []},
    to_ListTypeGroupAssignment: {
        results: [
            {
                AuthorisationGroup: 'AuthorisationGroup 1',
                ListTypeGroup: 'ListTypeGroup1',
                ListTypeGroupDescription: 'ListTypeGroupDescription 1',
                ParentKey: '8ae25d47-c3cc-4ee3-a040-ea00505692111',
                __metadata: {}
            },
            {
                AuthorisationGroup: 'AuthorisationGroup 2',
                ListTypeGroup: 'ListTypeGroup2',
                ListTypeGroupDescription: 'ListTypeGroupDescription 2',
                ParentKey: '34bcdc74-ab42-4538-8657-0a2b0473fcb7',
                __metadata: {}
            },
            {
                AuthorisationGroup: 'AuthorisationGroup 3',
                ListTypeGroup: 'ListTypeGroup3',
                ListTypeGroupDescription: 'ListTypeGroupDescription 3',
                ParentKey: '34bcdc74-ab42-4538-8657-0a2b0473fcb5',
                __metadata: {}
            }
        ]
    }
}, {
    __metadata: {
        aaa: 333,
        bbb: 444
    },
    to_ExcludedTerms: {results: []},
    to_ListTypeGroupAssignment: {
        results: [
            {
                AuthorisationGroup: 'AuthorisationGroup 6',
                ListTypeGroup: 'ListTypeGroup6',
                ListTypeGroupDescription: 'ListTypeGroupDescription 6',
                ParentKey: '8ae25d47-c3cc-4ee3-a040-ea00505692116',
                __metadata: {}
            },
            {
                AuthorisationGroup: 'AuthorisationGroup 7',
                ListTypeGroup: 'ListTypeGroup7',
                ListTypeGroupDescription: 'ListTypeGroupDescription 7',
                ParentKey: '34bcdc74-ab42-4538-8657-0a2b0473fcb7',
                __metadata: {}
            },
            {
                AuthorisationGroup: 'AuthorisationGroup 8',
                ListTypeGroup: 'ListTypeGroup8',
                ListTypeGroupDescription: 'ListTypeGroupDescription 8',
                ParentKey: '34bcdc74-ab42-4538-8657-0a2b0473fcb8',
                __metadata: {}
            }
        ]
    }
}
];

var aProperties = [
    "to_ListTypeGroupAssignment/ListTypeGroup",
    "to_ListTypeGroupAssignment/ListTypeGroupDescription"
];
// (End of sample data)

// Call the function to get the result:
var aSelectedDataSet = extract(oDataSet, aProperties);

// For this snippet only: output the result in readable format
document.write('<pre>'+JSON.stringify(aSelectedDataSet, 0, 4)+'</pre>');

Explanation of the algorithm:

The code is commented. This is how the algorithm works:

  • The function is recursive and takes the current data, which will be just a sub section of the original data once the function is called recursively.
  • The function also takes the path-style properties to select. Also this list will be shorter as the function is called recursively, so it only has those entries that are still relevant to the data section.
  • The third argument is the path that has already been traversed. At the initial call this is just the empty string, but as the recursion kicks in, it will become 'to_ListTypeGroupAssignment/', and later even 'to_ListTypeGroupAssignment/ListTypeGroup/' (always with terminating slash).
  • Each call of the function will return a part of the given data that matches the (path-style) selection.
  • The function starts by identifying the type of the data: whether it is a primitive value (a string, number, boolean), or an array (which is the case at the initial call), or an (non-array) object.
  • If it is an array, the function is just called recursively for each element without adding anything to the path. The result of each call is then stored in an array, which becomes the return value.
  • If it is a primitive value, it means we recursed to a "leaf" in the "tree". And since we got here, we may assume the "path" was matching up until this point, and so the primitive value must be returned so it can be added to the result
  • It it is an object, the select paths are traversed to see if the next level in those paths matches with an object property of the current data. If so, that property value is passed via a recursive call, while also adding that piece of the path to the "current" path

There are obviously the exceptions for __metadata and results, which are treated separately in the code.

这篇关于如何两个对象之间的匹配值,并创造新的具有特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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