最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using map to access nested json in react native - Stack Overflow

programmeradmin2浏览0评论

I am trying to access keys and arrays in my json structure with Array.map() but I'm missing something. Here's my JSON:

    {
    "payload": [
  {
    "id": 1,
    "name": "Atta",
    "brands": [
      {
        "id": 118,
        "name": "Wheatola",
        "subProducts": [
          {
            "id": 858,
            "name": "Chakki Aata",
            "minPrice": 52,
            "maxPrice": 56
          },
          {
            "id": 2,
            "name": "Chakki Atta",
            "minPrice": 222,
            "maxPrice": 236
          }
        ]
      }
    ]
  },
  {
    "id": 16,
    "name": "Rice (Branded)",
    "brands": [
      {
        "id": 25,
        "name": "CookStar",
        "subProducts": [
          {
            "id": 1163,
            "name": "Best Basmati",
            "creditDays": 0,
            "minPrice": 5600,
            "maxPrice": 5600
          },
          {
            "id": 863,
            "name": "Extra Long Grain Basmati",
            "creditDays": 0,
            "minPrice": 7800,
            "maxPrice": 7800
          }
        ]
      }
    ]
  }
]
  }

I want to access payload.name, payload.brands.name(s), payloads.brands.subproducts.name(s) with Array.map() and render the values in ponents. How do I access nested json like using map()? Expected output is:

Atta, Wheatola, Chakki Aata
Atta, Wheatola, Chakki Aata
Rice (Branded), Cookstar, Best Basmati
Rice (Branded), Cookstar, Extra Long Grain Basmati

I am trying to access keys and arrays in my json structure with Array.map() but I'm missing something. Here's my JSON:

    {
    "payload": [
  {
    "id": 1,
    "name": "Atta",
    "brands": [
      {
        "id": 118,
        "name": "Wheatola",
        "subProducts": [
          {
            "id": 858,
            "name": "Chakki Aata",
            "minPrice": 52,
            "maxPrice": 56
          },
          {
            "id": 2,
            "name": "Chakki Atta",
            "minPrice": 222,
            "maxPrice": 236
          }
        ]
      }
    ]
  },
  {
    "id": 16,
    "name": "Rice (Branded)",
    "brands": [
      {
        "id": 25,
        "name": "CookStar",
        "subProducts": [
          {
            "id": 1163,
            "name": "Best Basmati",
            "creditDays": 0,
            "minPrice": 5600,
            "maxPrice": 5600
          },
          {
            "id": 863,
            "name": "Extra Long Grain Basmati",
            "creditDays": 0,
            "minPrice": 7800,
            "maxPrice": 7800
          }
        ]
      }
    ]
  }
]
  }

I want to access payload.name, payload.brands.name(s), payloads.brands.subproducts.name(s) with Array.map() and render the values in ponents. How do I access nested json like using map()? Expected output is:

Atta, Wheatola, Chakki Aata
Atta, Wheatola, Chakki Aata
Rice (Branded), Cookstar, Best Basmati
Rice (Branded), Cookstar, Extra Long Grain Basmati
Share Improve this question edited Oct 2, 2017 at 7:07 Shubham Khatri 282k58 gold badges431 silver badges411 bronze badges asked Oct 2, 2017 at 7:06 Mayur BhangaleMayur Bhangale 3961 gold badge5 silver badges19 bronze badges 2
  • Could you provide a little bit code of your ponent (the render should be enough)? Do you save the json in your state? – Nocebo Commented Oct 2, 2017 at 7:14
  • I'd remend you make an entire algorithm to build an array with all the data you're looking for. – Andrew Commented Oct 2, 2017 at 7:19
Add a ment  | 

3 Answers 3

Reset to default 4

You need to nest Array.map()

 var data =  {
    "payload": [
  {
    "id": 1,
    "name": "Atta",
    "brands": [
      {
        "id": 118,
        "name": "Wheatola",
        "subProducts": [
          {
            "id": 858,
            "name": "Chakki Aata",
            "minPrice": 52,
            "maxPrice": 56
          },
          {
            "id": 2,
            "name": "Chakki Atta",
            "minPrice": 222,
            "maxPrice": 236
          }
        ]
      }
    ]
  },
  {
    "id": 16,
    "name": "Rice (Branded)",
    "brands": [
      {
        "id": 25,
        "name": "CookStar",
        "subProducts": [
          {
            "id": 1163,
            "name": "Best Basmati",
            "creditDays": 0,
            "minPrice": 5600,
            "maxPrice": 5600
          },
          {
            "id": 863,
            "name": "Extra Long Grain Basmati",
            "creditDays": 0,
            "minPrice": 7800,
            "maxPrice": 7800
          }
        ]
      }
    ]
  }
]
}

const renderData = data.payload.map((payload) => {
    return payload.brands.map(brand =>{
        return brand.subProducts.map(subProduct => {
          return `${payload.name}, ${brand.name}, ${subProduct.name}`
        }).join("\n")
    }).join("\n")
}).join("\n")

console.log(renderData);

Here might be a working example (without styling or anything):

  render() {
        return (
            <div>
                {
                    json.payload.map(j =>
                     <div>
                         {j.name}
                         {j.brands.map(b =>
                             <div>
                                 {b.name}
                                 {b.subProducts.map(s =>
                                     <div>
                                         {s.name}
                                     </div>)
                                 }
                             </div>
                         )}
                     </div>
                    )
                }
            </div>
        );
    }

You probably need to style it, or bine it with a table and columns, because it just renders the values now.

You can also use forEach since you'll have to nest map calls but you expect a flat array (?) in the end :

var json = {
  "payload": [{
      "id": 1,
      "name": "Atta",
      "brands": [{
        "id": 118,
        "name": "Wheatola",
        "subProducts": [{
            "id": 858,
            "name": "Chakki Aata",
            "minPrice": 52,
            "maxPrice": 56
          },
          {
            "id": 2,
            "name": "Chakki Atta",
            "minPrice": 222,
            "maxPrice": 236
          }
        ]
      }]
    },
    {
      "id": 16,
      "name": "Rice (Branded)",
      "brands": [{
        "id": 25,
        "name": "CookStar",
        "subProducts": [{
            "id": 1163,
            "name": "Best Basmati",
            "creditDays": 0,
            "minPrice": 5600,
            "maxPrice": 5600
          },
          {
            "id": 863,
            "name": "Extra Long Grain Basmati",
            "creditDays": 0,
            "minPrice": 7800,
            "maxPrice": 7800
          }
        ]
      }]
    }
  ]
}

var result = [];

json.payload.forEach(product => {
  product.brands.forEach(brand => {
    brand.subProducts.forEach(subProduct => {
      result.push([product.name, brand.name, subProduct.name].join(', '));
    });
  });
});

console.log(result);

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>