循环通过对象搜索属性并在成功时修改原始对象

时间:2016-03-18 15:15:03

标签: javascript arrays performance javascript-objects

var myObj = 
    data: {
    {
    chairId: "CHAIRCHROME009",    
    relatedOrders: [
        {
            someProp: 45423234,
            data : {
                firstOrder: {},
                relatedOrders: [
                    {
                        someProp: 5757587,
                        data : {
                            firstOrder: {},
                            relatedOrders: [ ],
                            notifications: [
                                {
                                    notificationId: "CHAIR-0909FF",
                                    latestNotification: {                                
                                        latestNotificationAction: "New",
                                        priority: "High",                                
                                    }
                                }
                            ],
                            relations: [ ]
                        }
                    }
                ],
                relations: [ ]
            }
        }
    ],
    relations: [ ]
}
}

如何无休止地遍历包含数组和对象的对象,实质上是搜索notifications属性。

在上面的示例中,通知在myObj的深度为2级,但可能是1级或100级。始终会在notifications下找到relatedOrders我需要确定notifications.latestNotification.latestNotificationAction

的值

如果未找到通知,则应返回nullfalse

我试过了:

function isThereRelatedOrders(myObj) {
    for(var k in myObj) {
        var v = myObj[k];

        if (k === "relatedOrders") {                
            isThereData(v[0]);
        }
    }
}

function isThereData(relatedOrder) {
    for(var y in relatedOrder) {
        var t = relatedOrder[y];

        if (y === "data") {                
            isThereNotification(t);
        }
    }
}

function isThereNotification(t) {
    for(var x in t) {            
        var j = t[x];

        if (x === "notifications") {
            console.lig('notifications found');
            if(j[0].latestNotification.latestNotificationAction  === "New") {                
                console.log('is new alert');
                // Add a property to my original myObj root level of alert: new
            }
            else {                
                console.log('is old alert');
                // Add a property to my original myObj root level of alert: old
            }
        }
        else if(x === "relatedOrders") {
            alert('SUB relatedOrders found');
            isThereRelatedOrders(j[0]);
        }
        else {
            alert('no notifications found');
        }
    }
}

isThereRelatedOrders(myObj);

有了上述内容,一旦我的代码第二次调用isThereRelatedOrders(),它就永远不会命中if语句..我猜它现在需要寻找.data ??

通过上面的执行,我希望重新发布这样的东西:

var myObj = {
    chairId: "CHAIRCHROME009",
    alert: "New"
    ////////

3 个答案:

答案 0 :(得分:3)

此提案使用迭代和递归方法来获取所需属性ActiveSheet.SaveAs Filename:=varDirectory, FileFormat:=xlOpenXMLWorkbookMacroEnabled 及其内容。如果找到,则将内容推送到notifications数组中。如果找不到任何内容,则数组仍为空。

result

编辑:

尊重function iter(o) { if (Array.isArray(o)) { o.forEach(iter); return; } if (typeof o === 'object') { Object.keys(o).forEach(function (k) { if (k === 'chairId') { chairId = o[k]; } if (k === 'notifications') { o[k].forEach(function (a) { if ('latestNotificationAction' in a.latestNotification) { result.push({ chairId: chairId, alert: a.latestNotification.latestNotificationAction }); } }); } iter(o[k]); }); } } var myObj = { data: { chairId: "CHAIRCHROME009", relatedOrders: [{ someProp: 45423234, data: { firstOrder: {}, relatedOrders: [{ someProp: 5757587, data: { firstOrder: {}, relatedOrders: [], notifications: [{ notificationId: "CHAIR-0909FF", latestNotification: { latestNotificationAction: "New", priority: "High", } }], relations: [] } }], relations: [] } }], relations: [] } }, chairId, result = []; iter(myObj); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');data属性之间切换的解决方案。

relatedOrders

答案 1 :(得分:2)

这是我的尝试,使用您的数据,但清理有效...点击“运行代码段”按钮运行它。

var myObj = {
  data: {
    chairId: "CHAIRCHROME009",
    relatedOrders: [{
      someProp: 45423234,
      data: {
        firstOrder: {},
        relatedOrders: [{
          someProp: 5757587,
          data: {
            firstOrder: {},
            relatedOrders: [],
            notifications: [{
              notificationId: "CHAIR-0909FF",
              latestNotification: {
                latestNotificationAction: "New",
                priority: "High",
              }
            }],
            relations: []
          }
        }],
        relations: []
      }
    }],
    relations: []
  }
};

function findAllNotifications(obj, chairId) {
  var result = [];
  Object.keys(obj).forEach(function(prop) {
    if (prop === 'chairId') {
      chairId = obj.chairId;
    }
    if (prop === 'notifications') {
      obj.notifications.forEach(function(notif) {
        result.push({
          chairId: chairId,
          alert: notif.latestNotification.latestNotificationAction
        });
      });
    }
    switch (typeof obj[prop]) {
      case 'object':
        result = result.concat(findAllNotifications(obj[prop], chairId));
        break;
      case 'array':
        obj[prop].forEach(function(sub) {
          result = result.concat(findAllNotifications(sub, chairId));
        });
        break;
    }
  });
  return result;
}

var result = findAllNotifications(myObj);
console.log("Result:", result);

// Doing this so you can see the result on the web page...
document.body.appendChild(document.createTextNode(JSON.stringify(result)));

// To "reassign" to the original object:
// myObj= findAllNotifications(myObj);

答案 2 :(得分:1)

JSONPath非常适合此类任务。它非常灵活,非常有趣。
您可以在此处下载实际的分支:https://github.com/s3u/JSONPath

1。简单的任务,简单的解决方案:

如果您的数据中只有一个主席,您可以轻松获取chairId并让JSONPath完成其余的工作:

var result = {
    chairId: myObj.data.chairId,
    alert: JSONPath({json: myObj, wrap: false, path: '$..latestNotificationAction'}) || false
};
var resultString = JSON.stringify(result, 0, 4);
document.write('<pre>' + resultString + '</pre>');
<script src="https://raw.githack.com/s3u/JSONPath/master/lib/jsonpath.js"></script>
<script>
var myObj = {
    data: {
        chairId: "CHAIRCHROME009",
        relatedOrders: [{
            someProp: 45423234,
            data: {
                firstOrder: {},
                relatedOrders: [{
                    someProp: 5757587,
                    data: {
                        firstOrder: {},
                        relatedOrders: [],
                        notifications: [{
                            notificationId: "CHAIR-0909FF",
                            latestNotification: {
                                latestNotificationAction: "New",
                                priority: "High",
                            }
                        }],
                        relations: []
                    }
                }],
                relations: []
            }
        }],
        relations: []
    }
};
</script>

2。复杂的任务,简单的解决方案:

如果您的数据更复杂,您可以使用回调函数,每次找到latestNotification的主席时都会调用该函数:

function find(obj, foundCallBack) {

  JSONPath({
      json: obj, resultType: 'parent', wrap: false, 
      path: '$..chairId', 
      callback: function(chair) {
          JSONPath({
              json: chair, resultType: 'parent', wrap: false, 
              path: '$..latestNotification', 
              callback: function(notification) {foundCallBack({
                  chairId: chair.chairId,
                  alert: notification.latestNotification.latestNotificationAction,
                  priority: notification.latestNotification.priority
              })}});
      }});
}
find(myObj, function(result){
   var resultString = JSON.stringify(result, 0, 4);
   alert(resultString);
   document.write('<pre>' + resultString + '</pre>');
});
<script src="https://raw.githack.com/s3u/JSONPath/master/lib/jsonpath.js"></script>
<script>
var myObj = {
    data: {
        employees: [1, 2, 3, 4],
        chairs: [
            {
                chairId: "CHAIRCHROME009",
                relatedOrders: [{
                    someProp: 45423234,
                    data: {
                        firstOrder: {},
                        relatedOrders: [{
                            someProp: 5757587,
                            data: {
                                firstOrder: {},
                                relatedOrders: [],
                                notifications: [{
                                    notificationId: "CHAIR-0909FF",
                                    latestNotification: {
                                        latestNotificationAction: "New1",
                                        priority: "High",
                                    }
                                },
                                    {
                                        notificationId: "CHAIR-0909FF",
                                        latestNotification: {
                                            latestNotificationAction: "New2",
                                            priority: "Medium",
                                        }
                                    }],
                                relations: []
                            }
                        }],
                        relations: []
                    }
                }],
                relations: []
            },
            {
                chairId: "CHAIRCHROME0077",
                relatedOrders: [{
                    someProp: 45423234,
                    data: {
                        firstOrder: {},
                        relatedOrders: [{
                            someProp: 5757587,
                            data: {
                                firstOrder: {},
                                relatedOrders: [],
                                notifications: [{
                                    notificationId: "CHAIR-090922FF",
                                    latestNotification: {
                                        latestNotificationAction: "New3",
                                        priority: "Low",
                                    }
                                }],
                                relations: []
                            }
                        }],
                        relations: []
                    }
                }],
                relations: []
            }
        ]
    }
};
</script>