javascript对象数组迭代

时间:2018-09-23 21:46:41

标签: javascript json loops iteration

我有如下的Json数据;

  let data = [
  {
    "name": "John Doe",
    "position": "Accountant",
    "social": ["facebook", "instagram", "youtube", "pinterest"]
  },
  {
    "name": "Michael Schumaher",
    "position": "F1 Pilot",
    "social": ["facebook", "instagram", "youtube", "pinterest"]
  }
];

我需要循环遍历节点和称为“社交”的子数组。

let html = '';
let i;

for ( i = 0; i < data.length; i++) {

   let socArr = data[i].social;

   socArr.forEach ( function ( item ) {
     console.log( item + '/');
   });
};

我需要在同一div中显示“ name position social”,但是forEach循环为我提供了json文档中的所有数组数据。

2 个答案:

答案 0 :(得分:2)

关于您的问题,我假设您只需要两个div元素。因此,对于这种情况,我将在您的html div中创建两个静态变量body,然后用该循环为它们提供数据。请参见下面的示例:

let data = [
    {
        "name": "John Doe",
        "position": "Accountant",
        "social": ["facebook", "instagram", "youtube", "pinterest"]
    },
    {
        "name": "Michael Schumaher",
        "position": "F1 Pilot",
        "social": ["facebook", "instagram", "youtube", "pinterest"]
    }
];

for (let i = 0; i < data.length; i++) {
    document.getElementById('myDiv' + (i + 1)).innerHTML = data[i].name + '<br/>' + data[i].position + '<br/>';
    let socArr = data[i].social;
    socArr.forEach ( function ( item ) {
        document.getElementById('myDiv' + (i + 1)).innerHTML += item + '<br/>';
    });
    document.getElementById('myDiv' + (i + 1)).innerHTML += '<br/>';
}
<div id="myDiv1"></div>
<div id="myDiv2"></div>

答案 1 :(得分:1)

我无法复制您声明的行为。您应该能够遍历每个记录(数组的元素),然后遍历其值:

let data = getData();
let body = document.querySelector('body')
let fragment = document.createDocumentFragment()  // used for performance
let text = (str) => document.createTextNode(str)  // used to reduce/simplify code
let br = () => document.createElement('br')       // used to reduce/simplify code

data.forEach(rcd => {
  // create new div for each record
  let div = document.createElement('div')

  // iterate over record values
  for (let value of Object.values(rcd)) {
    div.appendChild(text(value))
    div.appendChild(br())
  }

  // add to fragment
  fragment.appendChild(div)
});

// add to DOM
body.appendChild(fragment);



// Data structure is placed in function so logic SO is seen first
function getData() {
  return [{
      "name": "John Doe",
      "position": "Accountant",
      "social": ["facebook", "instagram", "youtube", "pinterest"]
    },
    {
      "name": "Michael Schumaher",
      "position": "F1 Pilot",
      "social": ["facebook", "instagram", "youtube", "pinterest"]
    }
  ]
}
div {
  border: 1px solid;
  padding: .5rem;
  margin: 1em
}