从嵌套的json对象中检索值

时间:2017-03-10 17:24:49

标签: javascript json filter lodash

我有以下json对象:

{
  "name": "Cairo",
  "title": "Lots to do in cairo",
  "categories": ["travel", "holiday"],
  "image": [
    {
      "thumbnail": {
        "src": "/images/thumbnail/cairo.jpg",
        "height": 27,
        "width": 60
      }
    },
    {
      "mobile": {
        "src": "/images/mobile/cairo.jpg",
        "height": 106,
        "width": 236
      }
    },
    {
      "original": {
        "src": "/images/original/cairo.jpg",
        "height": 866,
        "width": 1920
      }
    }
  ]
}

我试图访问' src' '原创'的价值使用jquery / lodash / javascript对此特定对象的图像。

我可以使用以下内容输出值:

var originalSrc = _.result(obj, 'image[2].original.src');

这个问题是我必须对[2]进行硬编码,但是这个json响应中的图像变体的排序并没有固定,所以下次它可以返回' mobile&# 39; src而不是。

有没有人对此有任何解决方案/想法?

由于

Ashil

4 个答案:

答案 0 :(得分:0)

JSON的布局很差(正如上面的评论所指出的那样),但是如果你不能改变它,那么这个单行应该可以工作:

obj.image.filter(function (x) { return Object.keys(x)[0] == 'original' })[0].original.src

答案 1 :(得分:0)

可以试试这个:

var json = {
  "name": "Cairo",
  "title": "Lots to do in cairo",
  "categories": ["travel", "holiday"],
  "image": [
    {
      "thumbnail": {
        "src": "/images/thumbnail/cairo.jpg",
        "height": 27,
        "width": 60
      }
    },
    {
      "mobile": {
        "src": "/images/mobile/cairo.jpg",
        "height": 106,
        "width": 236
      }
    },
    {
      "original": {
        "src": "/images/original/cairo.jpg",
        "height": 866,
        "width": 1920
      }
    }
  ]
}

var desiredObject = json.image.filter(function(image){return Object.keys(image)[0] == 'original'; })[0]

console.log(desiredObject);
console.log(desiredObject.original.src);

答案 2 :(得分:0)

您可以尝试通过多个步骤实现解决方案。

  1. 获取对象属性,在您的情况下,thumbnail, mobile, original是图像对象内数组内对象的属性。
    Object.keys(objJSON.image)检索数组中的所有属性,在这种情况下,因为它是一个数组,结果将是[0,1,2]

  2. 在Image对象中查找“原始”Image对象。可以使用object["PropertyName"]语法访问对象中的属性,find方法返回与条件匹配的第一个元素。所以,基本上,我们试图找到包含名为“original”的属性的对象。

    Object.keys(objJSON.image).find(i => objJSON.image[i]["original"]);

  3. 从对象中检索src属性。 objJSON.image[originalImageIndexInArray].original.src;

    var objJSON = {
      "name": "Cairo",
      "title": "Lots to do in cairo",
      "categories": ["travel", "holiday"],
      "image": [
        {
          "thumbnail": {
            "src": "/images/thumbnail/cairo.jpg",
            "height": 27,
            "width": 60
          }
        },
        {
          "mobile": {
            "src": "/images/mobile/cairo.jpg",
            "height": 106,
            "width": 236
          }
        },
        {
          "original": {
            "src": "/images/original/cairo.jpg",
            "height": 866,
            "width": 1920
          }
        }
      ]
    };
    
    var originalImageIndexInArray = Object.keys(objJSON.image).find(i => objJSON.image[i]["original"]);
    
    var originalImageSrc = objJSON.image[originalImageIndexInArray].original.src;
    
    console.log(originalImageSrc);

答案 3 :(得分:0)

您可以使用findimage数组中获取带有src键的项目,使用get获取data.image。请注意,我们需要使用chain通过find将数组转换中的方法var result = _.chain(data.image) .find('original') .get('original.src') .value(); 链接到对象中。

var data = {
  "name": "Cairo",
  "title": "Lots to do in cairo",
  "categories": ["travel", "holiday"],
  "image": [
    {
      "thumbnail": {
        "src": "/images/thumbnail/cairo.jpg",
        "height": 27,
        "width": 60
      }
    },
    {
      "mobile": {
        "src": "/images/mobile/cairo.jpg",
        "height": 106,
        "width": 236
      }
    },
    {
      "original": {
        "src": "/images/original/cairo.jpg",
        "height": 866,
        "width": 1920
      }
    }
  ]
};

var result = _.chain(data.image)
  .find('original')
  .get('original.src')
  .value();
  
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
var result = _(data.image).map('original.src').first();

另一种解决方案是使用map获取图片来源,然后使用first获取值。

var data = {
  "name": "Cairo",
  "title": "Lots to do in cairo",
  "categories": ["travel", "holiday"],
  "image": [
    {
      "thumbnail": {
        "src": "/images/thumbnail/cairo.jpg",
        "height": 27,
        "width": 60
      }
    },
    {
      "mobile": {
        "src": "/images/mobile/cairo.jpg",
        "height": 106,
        "width": 236
      }
    },
    {
      "original": {
        "src": "/images/original/cairo.jpg",
        "height": 866,
        "width": 1920
      }
    }
  ]
};

var result = _(data.image).map('original.src').first();
  
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
    <link href='//fonts.googleapis.com/css? family=Open+Sans:400italic,600italic,700italic,400,600,700' type='font- family'>


    <style> 
        body        {background-color: white;}
        h4          {color: black; font-family: 'Open Sans', sans- serif; text-align: center; font-size: 20px;}
        h3          {color: black; font-family: 'Open Sans', sans- serif; text-align: center; font-size: 15px; margin-bottom:                                10px;}
        p               {color: black; font-family: 'Open Sans',  sans-serif; text-align: center; font-size: 12px;}
  label     {color: black; font-family: 'Open Sans', sans-serif;  text-align: center; font-size: 12px;}
  img           {margin: auto; display: block; max-width: 100%;}
  button    {padding: 10px; width: 200px; display: block;  margin:auto;}
  .apt2b    {
        border: 1px;
        margin: auto;
        text-align: center;
        padding: 10px;
        max-width: 100%;
  }

   * Smartphones (portrait and landscape) ----------- */
 @media only screen 
 and (min-device-width : 320px) 
 and (max-device-width : 480px) {
 /* Styles */
 }

 /* Smartphones (landscape) ----------- */
 @media only screen 
 and (min-width : 321px) {
 /* Styles */
 }

 /* Smartphones (portrait) ----------- */
 @media only screen 
 and (max-width : 320px) {
 /* Styles */
 }

 /* iPads (portrait and landscape) ----------- */
 @media only screen 
 and (min-device-width : 768px) 
 and (max-device-width : 1024px) {
 /* Styles */
 }

 /* iPads (landscape) ----------- */
 @media only screen 
 and (min-device-width : 768px) 
 and (max-device-width : 1024px) 
 and (orientation : landscape) {
 /* Styles */
 }

 /* iPads (portrait) ----------- */
 @media only screen 
 and (min-device-width : 768px) 
 and (max-device-width : 1024px) 
 and (orientation : portrait) {
 /* Styles */
 }

 /* Desktops and laptops ----------- */
 @media only screen 
 and (min-width : 1224px) {
 /* Styles */
 }

 /* Large screens ----------- */
 @media only screen 
 and (min-width : 1824px) {
 /* Styles */
 }

 /* iPhone 4 ----------- */
 @media
 only screen and (-webkit-min-device-pixel-ratio : 1.5),
 only screen and (min-device-pixel-ratio : 1.5) {
 /* Styles */
 }
    </style>


<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>

<meta charset="utf-8" />
<meta content="IE=edge" http-equiv="X-UA-Compatible" />
<meta content="width=device-width, maximum-scale=1.0, initial-  scale=1.0" name="viewport" />

</head>


<body width = "device-width">
<div>   
<div>
   <img src="http://restorationmodern.com/Melanie/unsubscribe_banner_2.png">
</div>
 <div  class="apt2b">
   <h4>Don’t move out. We’ll even let you hold the remote to the TV.     </h4>
        <p>
    See how empty that sofa up there looks without you? We have   chips, we have soda, we have Netflix. We even have a pup. Don't leave! 
  </p>
  <h3>Just decide how cozy we should get:</h3>
<div>
<form action="" method="POST">
   <input type="hidden" name="$fields" value="EmailFrequency" />

<input id="regular" name="EmailFrequency" type="radio" value="All" />
   <label for="regular"><span></span><b>Send me all your emails.</b>         Let’s move in together. Adopt a puppy. Drink out of the same milk carton.       </label><br />

       <input checked="checked" id="email_frequency_weekly"    name="EmailFrequency" type="radio" value="weekly"/>
  <label for="email_frequency_weekly"><span></span><b>Send me a   monthly roundup of all the great stuff going on.</b> I like you, APT2B.   But not that much, so let's be neighbors. </label><br />
   <br>

   <h3>Or are you a topics connoisseur?</h3>

    <input id="regular" name="EmailFrequency" type="checkbox"  value=“newarrivals” />
   <label for="regular"><span></span> <b>Send me your new arrivals emails.</b> I need to stay on top of trends. Not subscribing to these is so 2016 after all.</label><br />

  <input id="regular" name="EmailFrequency" type="checkbox" value=“sales” />
  <label for="regular"><span></span><b>Send me all your sales emails.   </b> Nothing feels as relaxing as putting your feet up on a half-priced ottoman. </label><br />

 <input id="regular" name="EmailFrequency" type="checkbox"  value=“ideasandinspiration” />
  <label for="regular"><span></span> <b>Send me your ideas and inspirations emails.</b> Be the Thurman to my Tarantino. Let's not make three, two hour movies though.</label><br />

 <input id="regular" name="EmailFrequency" type="checkbox" value=“contestsandgiveaways” />
  <label for="regular"><span></span><b>Send me your contest and giveaway emails.</b> Win something without leaving my sofa? Uhm, yes please!</label><br />
  <br>

       <h3>Moved to another planet and don't need furniture anymore? </h3>

   <input id="email_frequency_unsubscribe" name="EmailFrequency"  type="radio" value="$unsubscribe" /> 
   <label for="email_frequency_unsubscribe"><span></span><b>  Unsubscribe me from all emails.</b> I’m done! I’m moving back to Kansas  to live with my parents.</label><br/>

   <script>
    $('input[type=radio]').change(function(){
 if($('input[type=radio]:checked').length > 0)
    $('input[type=checkbox]').removeAttr('checked');
 });

$('input[type=checkbox]').change(function(){
if($('input[type=checkbox]:checked').length > 0)
    $('input[type=radio]').removeAttr('checked');
});
</script>

<br>
  <br>
   <button type="submit">Update Preferences</button>
 </form>
  </div>
 </div>
 </div>
 </body>
</html>`

相关问题