简体   繁体   中英

how to access nested json array

I'm trying to access data in the following array but am having trouble using .forEach I want to access all singleLine.text but it won't let me. I am guessing because there are multiple singleLines at the same level.

var a = [ 
  { boxedCharacters: { text: '1040043' } },
  { singleLine: { text: '東京都中央区日本橋新古町' } },
  { singleLine: { text: 'この度は、数多くのお店の中から当店を'} },
  { singleLine: { text: 'お選びご来店頂きまして誠にありがとう'} }
]

 a.forEach(function(value){
      console.log(value.singleLine.text)
      })

I've tried this but it isn't the best solution since it'll create an empty array for boxedCharacters because it won't match the passed in property value. Also, I could have multiple boxedCharaters and other keys with the same name.

function genNewArray(jsonArray)
 {return results.map(function(a){
 return {[jsonArray]: a[jsonArray]}
 })
}

var i = genArray(‘singleLine’)

Any better ideas of how I could access the values?

$.each(a, function(entryIndex, entry) {
  $.each(this.singleLine, function() { 
    alert(this.text); 
  }); 
 });

In first case it is failing because of this console.log(value.singleLine.text) . Because the array also have a key named boxedCharacters and inside the forEach when the item is { boxedCharacters: { text: '1040043' } }, it will not find value.singleLine . so it will fail

 var a = [{ boxedCharacters: { text: '1040043' } }, { singleLine: { text: '東京都中央区日本橋新古町' } }, { singleLine: { text: 'この度は、数多くのお店の中から当店を' } }, { singleLine: { text: 'お選びご来店頂きまして誠にありがとう' } } ] a.forEach(function(value) { if (value.singleLine) { console.log(value.singleLine.text) } }) 

You could try the following:

  const a = [ { boxedCharacters: { text: '1040043' } }, { singleLine: { text: '東京都中央区日本橋新古町' } }, { singleLine: { text: 'この度は、数多くのお店の中から当店を'} }, { singleLine: { text: 'お選びご来店頂きまして誠にありがとう'} } ]; const getSingleLine = o => (o&&o.singleLine); const getText = o => (o&&o.text); const getSingleLineText = o => getText(getSingleLine(o)) console.log( a.map(getSingleLineText) .filter(x=>!!x)//remove undefined ) 

Or you could reduce the object to the value and if the value doesn't exist return undefined:

const tryGet = keys => object =>
  keys.reduce(
    (o,key)=>
      (o!==undefined && o[key]!==undefined)
        ? o[key]
        : undefined,
    object
  );

const getSingleLineText = tryGet(["singleLine","text"]);

console.log(
  a.map(getSingleLineText)
  .filter(x=>!!x)//remove undefined
);

You just need to test whether there is value for singleLine or not..

a.forEach(function(value){
  if(a.singleLine) console.log(value.singleLine.text)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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