从多维对象中获取价值?

时间:2017-12-30 08:59:02

标签: javascript multidimensional-array

我正在尝试使用JavaScript从多维对象中获取值。我试过.filter,但它似乎只在数组上工作。另外,我几乎用UnderscoreJS的{​​{1}}来做,但它只适用于非多维对象。它甚至可能,或者我必须重建我的对象?我会感激任何提示......请帮助:'(

代码(https://jsfiddle.net/ob58fye2/):

_where

1 个答案:

答案 0 :(得分:0)

您可以循环到JSON数组并获得所需的结果。



var configurators = JSON.parse('{"ConfiguredItems":{"OtapiConfiguredItem":[{"Id":"3667395302656","Quantity":"2981","Configurators":{"ValuedConfigurator":[{"@attributes":{"Pid":"1627207","Vid":"3224419"}},{"@attributes":{"Pid":"20509","Vid":"28383"}}]}},{"Id":"3667395302655","Quantity":"4145","Configurators":{"ValuedConfigurator":[{"@attributes":{"Pid":"1627207","Vid":"129819"}},{"@attributes":{"Pid":"20509","Vid":"28383"}}]}},{"Id":"3667395302654","Quantity":"0","Configurators":{"ValuedConfigurator":[{"@attributes":{"Pid":"1627207","Vid":"80557"}},{"@attributes":{"Pid":"20509","Vid":"28383"}}]}}]}}');

function FindConfigurator(pid, vid) {
    var id = null;
    configurators.ConfiguredItems.OtapiConfiguredItem.forEach(
    (OtapiConfiguredObj)=>{
    OtapiConfiguredObj.Configurators.ValuedConfigurator.forEach(
    (ValuedConfiguratorObj)=>{
    if(ValuedConfiguratorObj['@attributes'].Pid === pid.toString() && ValuedConfiguratorObj['@attributes'].Vid === vid.toString()){
      id = OtapiConfiguredObj.Id;
    }
    });
    });
    console.log(configurators); // Returns the configurators.
    console.log(id); // Should return `3667395302656`.
}

FindConfigurator(1627207, 3224419);




因为,你不能在break中添加forEach语句,你可以有一个通用的循环来这样做,这样当找到匹配时,循环就会被破坏。



var configurators = JSON.parse('{"ConfiguredItems":{"OtapiConfiguredItem":[{"Id":"3667395302656","Quantity":"2981","Configurators":{"ValuedConfigurator":[{"@attributes":{"Pid":"1627207","Vid":"3224419"}},{"@attributes":{"Pid":"20509","Vid":"28383"}}]}},{"Id":"3667395302655","Quantity":"4145","Configurators":{"ValuedConfigurator":[{"@attributes":{"Pid":"1627207","Vid":"129819"}},{"@attributes":{"Pid":"20509","Vid":"28383"}}]}},{"Id":"3667395302654","Quantity":"0","Configurators":{"ValuedConfigurator":[{"@attributes":{"Pid":"1627207","Vid":"80557"}},{"@attributes":{"Pid":"20509","Vid":"28383"}}]}}]}}');

function FindConfigurator(pid, vid) {
    var id = null;
    for(var i=0; i<configurators.ConfiguredItems.OtapiConfiguredItem.length; i++){
    var OtapiConfiguredObj = configurators.ConfiguredItems.OtapiConfiguredItem[i];
     for(var j=0; j< OtapiConfiguredObj.Configurators.ValuedConfigurator.length; j++) {
      var ValuedConfiguratorObj = OtapiConfiguredObj.Configurators.ValuedConfigurator[j];
      if(ValuedConfiguratorObj['@attributes'].Pid === pid.toString() && ValuedConfiguratorObj['@attributes'].Vid === vid.toString()){
      id = OtapiConfiguredObj.Id;
      break;
      }
     }
     if(id){break;}
    }  
    console.log(configurators); // Returns the configurators.
    console.log(id); // Should return `3667395302656`.
}

FindConfigurator(1627207, 3224419);
&#13;
&#13;
&#13;