使用递归搜索对对象中的数组进行排序

时间:2015-12-10 07:48:41

标签: javascript arrays node.js object

我正在尝试使用Node.js在JSON-Object中按名称对每个Array进行排序。 我设法使用Underscore.js对数组进行排序,但是如何输入整个Object并让对象重新排序?

考虑以递归方式查看对象并对其中的每一个进行排序,但我该怎么做呢?

这是一个示例对象,只是对数组进行排序:

    var _ = require("./underscore.js")
    var jsonObject = {  "Configuration":{  
          "$":{  
             "xmlns":"http://www.example.com/"
          },
          "ApplicationInstance":{  
             "Description":"Description text here.",
             "Name":"Server1",
             "Class":"System",
             "Visibility":"System",
             "CustomerCreated":"0",
             "Active":"0",
             "IntroducedIn":{  
                "$":{  
                   "xsi:nil":"true",
                   "xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance"
                }
             },
             "Property":[  
                {  
                   "Description":"JMS publisher destination type.",
                   "Name":"jmsJBossPublisher.destinationType",
                   "Class":"System",
                   "Visibility":"System",
                   "LanguageIndependantDescriptionKey":"ActivityGateway-JMSSenderConfiguration.jmsJBossPublisher.destinationType.DESCKEY",
                   "LanguageIndependantNameKey":"ActivityGateway-JMSSenderConfiguration.jmsJBossPublisher.destinationType.NAMEKEY",
                   "CustomerCreated":"1",
                   "Active":"0",
                   "IntroducedIn":"1.1",
                   "AttributeValue":"QUEUE",
                   "AttributeDataTypeName":"String"
                },
                {  
                   "Description":"jmsConnectionFactory properties.",
                   "Name":"jmsConnectionFactory.jndiNameForJmsConnectionFactory",
                   "SecurityClass":"System",
                   "Visibility":"System",
                   "LanguageIndependantDescriptionKey":"ActivityGateway-JMSSenderConfiguration.jmsConnectionFactory.jndiNameForJmsConnectionFactory.DESCKEY",
                   "LanguageIndependantNameKey":"ActivityGateway-JMSSenderConfiguration.jmsConnectionFactory.jndiNameForJmsConnectionFactory.NAMEKEY",
                   "CustomerCreated":"1",
                   "Active":"0",
                   "IntroducedIn":"1.1",
                   "AttributeValue":"ConnectionFactory",
                   "AttributeDataTypeName":"String"
                }
             ],
             "ServerId":"1",
             "ApplicationName":"ActivityGateway",
             "InstanceID":"1"
          }
       }
    };
    console.log(_.sortBy(jsonObject.Configuration.ApplicationInstance.Property,'Name'))

1 个答案:

答案 0 :(得分:1)

_.sortBy返回一个克隆数组,因此您需要覆盖以前的值。 尝试添加以下行:

jsonObject.Configuration.ApplicationInstance.Property = _.sortBy(jsonObject.Configuration.ApplicationInstance.Property,'Name')