简体   繁体   English

我可以简化这个Javascript循环吗?

[英]Can I simplify this Javascript loop?

I may have gone around the most convoluted way to achieve this (see code below). 我可能已经绕过了最复杂的方法来实现此目的(请参见下面的代码)。 Could someone with experience tell me if there is a better way? 有经验的人可以告诉我是否有更好的方法吗?

I have two JSON objects resource and data . 我有两个JSON对象resourcedata I want to loop over each new item in data and if the key matches in resource replace the value for that key in resource with the value in data. 我想遍历data每个新项目,如果resource的键匹配,则用数据中的值替换resource中该键的值。 If this does not make sense the code I have below will. 如果这没有意义,我下面的代码将。

This works and does what I need it to do, but it does not feel right (don't laugh) 这行得通,可以完成我需要做的事情,但是感觉不对(不要笑)

factory.put = function (resource, data) {
        dataArr = [data];
        resourceArr = [resource];


        for (var i = 0; i < dataArr.length; i++) {
            var obj = dataArr[i];
            for (var key in obj) {
                var attrName = key;
                var attrValue = obj[key];


                for (var i = 0; i < resourceArr.length; i++) {
                    var obj = resourceArr[i];
                    for (var key in obj) {
                        var resourceArrName = key;
                        var resourceArrValue = obj[key];

                        if (resourceArrName == attrName){
                           resource[resourceArrName] = attrValue
                        }
                    }

                    }

                }
            }

           resource.put()
        }

Unless I'm missing something, you have no need to stuff the objects into arrays. 除非我缺少任何东西,否则您无需将对象填充到数组中。 You just loop through the attributes of one object, data , check if that attribute exists in the other object, resource , and if it does, replace the value in resource with that of data . 您只需遍历一个对象( data的属性,检查该属性是否存在于另一对象( resource ,如果存在,则用data替换resource的值。

for (var key in data) {
    var attrName = key;
    var attrValue = data[key];

    if(resource[attrName]) {
        resource[attrName] = attrValue;
    }
}

You don't need to iterate over resourceArr's keys. 您不需要遍历resourceArr的键。 Just check if resourceArr[key] exists, if so, set the value. 只需检查resourceArr [key]是否存在,如果存在,请设置该值。

Something like: 就像是:

if(resourceArr[key])
 resourceArr[key] = attrValue;

One way to simplify the loops, is to use the forEach function, which angular provides: 简化循环的一种方法是使用forEach函数,该函数可以提供以下功能:

factory.put = function (resource, data) {
    dataArr = [data];
    resourceArr = [resource];

    angular.forEach(dataArr, function(obj) {
        angular.forEach(obj, function(value, key) {
            angular.forEach(resourceArr, function(resourceObj) {
                if(resourceObj[key]) {
                    resourceObj[key] = value;
                }
            }
        }
    }

    resource.put()
}

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

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