Home > Software design >  How to create a list and anchor based on json object in jquery
How to create a list and anchor based on json object in jquery

Time:04-07

I am trying to create a list. It is created successfully. I want to add anchar link in each list item using targetProducts array. Arrays item should be in a separate anchor tag. I am attaching a code

$( document ).ready(function() {
    var listArray = [
  {
    message: "Total qty of SpO2 Connection Cables (JL-900P) are less than total qty of Bedsides",
    type: "HARD",
    targetProducts: [
      "BR-903PA",
      "BR-903PB",
      "BR-903PC"
    ]
  },
  {
    message: "Total qty of SpO2 Connection Cables (JL-900P) are less than total qty of Bedsides",
    type: "SOFT",
    targetProducts: [
      "AE-918P"
    ]
  },
  {
    message: "Total qty of SpO2 Connection Cables (JL-900P) are less than total qty of Bedsides",
    type: "SOFT",
    targetProducts: [
      "A/10-1600-030",
      "A/11-CA-403-12"
    ]
  },
  {
    message: "Total qty of SpO2 Connection Cables (JL-900P) are less than total qty of Bedsides",
    type: "HARD",
    targetProducts: [
      "A/2289PA"
    ]
  }
];
let listUL = $('<ul>');
 listArray.filter((item)=>{
    listUL.append('<li>' item.message ':<a href="#" onclick="clicked(event)">' item.targetProducts '</a></li>')
})
$('#custom-list').append(listUL);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="custom-list">
 <!-- append the list -->
</div>

Requirement: each array item should be in a separate anchor tag. it is coming in single anchor tag

CodePudding user response:

you need to loop through the target product array and append each item to li

$( document ).ready(function() {
        var listArray = [
      {
        message: "Total qty of SpO2 Connection Cables (JL-900P) are less than total qty of Bedsides",
        type: "HARD",
        targetProducts: [
          "BR-903PA",
          "BR-903PB",
          "BR-903PC"
        ]
      },
      {
        message: "Total qty of SpO2 Connection Cables (JL-900P) are less than total qty of Bedsides",
        type: "SOFT",
        targetProducts: [
          "AE-918P"
        ]
      },
      {
        message: "Total qty of SpO2 Connection Cables (JL-900P) are less than total qty of Bedsides",
        type: "SOFT",
        targetProducts: [
          "A/10-1600-030",
          "A/11-CA-403-12"
        ]
      },
      {
        message: "Total qty of SpO2 Connection Cables (JL-900P) are less than total qty of Bedsides",
        type: "HARD",
        targetProducts: [
          "A/2289PA"
        ]
      }
    ];
    let listUL = $('<ul>');
     listArray.filter((item)=>{
    var li=$('<li>' item.message '</li>')
    listUL.append(li);
       item.targetProducts.forEach(function(val){
       
       li.append('<a href="#" onclick="clicked(event)">' val '</a>,')
       
       })
    })
    $('#custom-list').append(listUL);
    
    });
  • Related