【问题标题】:How to check whether a json contains如何检查json是否包含
【发布时间】:2017-07-21 09:04:32
【问题描述】:

我有一个包含 JSON 对象的 javascript 数组,如下所示:-

var data :[{
         name:"ABC",
         categories:[{
                     name:"XYZ",
                     categories:[{
                           .
                            .
                             .
                              N
                        }]
              }]
}]

我想在这个数组中进行迭代,并想检查categories[] 是否存在和Categories[] 是否有任何值,如果是,则在其中插入数据

EG:

var mydata:[];
 mydata.push({name:"MNP",Categories:[]});

我想在类别中插入这些数据

【问题讨论】:

  • 您的 JSON 结构本身似乎很奇怪。考虑修改它。
  • json 是一个数组,而不是一个对象。但是要将内容保存到变量中,您必须使用 var x = y;= 而不是 :
  • @mtizziani 我不能在我的代码中使用 = 因为这个 json 是我基于 UI5 的应用程序的一部分。我的 JSON 绝对正确。
  • @ChandrasekarG 它似乎很奇怪,但我认为没有必要修改它。这个JSON是根据应用程序的要求
  • 这与 UI5 无关。即使在 UI5 中,var something: value 在语法上也是错误的。

标签: javascript jquery


【解决方案1】:
// this is a sample object containing 1 element is text and one element is an array
var object = {smapleA: 'some text', sampleB : ['stringArray']};

// init a var to save the status (intial it must be false)
var containsArray = false;

// go over each element in the object with this loop definition
for(let key in object){
   // for be clean check if object.key realy exists 
   if(object.hasOwnProperty(key){

     // here you check if the current element is an Array
     if(Array.isArray(object[key])){

       // set containsArray variable to true
       containsArray = true;
     }
   }
}

console.log(containsArray);

【讨论】:

    猜你喜欢
    • 2020-01-17
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    相关资源
    最近更新 更多