当我运行console.log
时,我可以看到JSON,我认为这个问题与我的return
语句有关。
import $ from 'jquery';
import headlineData from '../JSON/headline.json';
export default class {
constructor() {
this.loadHeadlineData();
}
// ------------------- //
loadHeadlineData() {
let res = headlineData.d.results.map(function(obj) {
return {
"Name": obj.preferredname,
"Initials": obj.initials,
"Title": obj.jobtitle,
"Office": obj.office
}
})
$("#headline-cont h1").append(res);
}
}
console.log(headlineData)
{
"d": {
"results": [{
"preferredname": "Bobson A. Dugnutt",
"initials": "BAD",
"jobtitle": "Coolguy",
"office": "New York"
}]
}
}
<div id="headline-cont">
<h1></h1>
</div>
console.log(JSON.stringify(headlineData.d.results))
:[{"preferredname":"Bobson A. Dugnutt","initials":"BAD","jobtitle":"Coolguy","office":"New York"}]
几点:
filter
内部,它应该是一个返回true
/ false
的表达式。 filter
接受一个数组,返回一个数组,其值为true
。例如。 [1,2,3].filter( n => n % 2 === 1 );
给[1,3]
。你想用map
吗?append
时,我们应该添加jQuery DOM对象,例如$(...).append($("<h1>"+res+"</h1>"));
;你想用text()
吗? (如果<h1>
已经存在)如果没有,你可以改为从选择器中删除h1
并使用append
。res
是一个阵列(无论使用map
还是filter
)。你可能想最终使用res[0].Name
。但是,如果您确实想要输出整个数组/ json,请使用JSON.stringify
。使用,
分隔选择器中使用的两个类
$(".headline-cont,h1")
var headlineData={
"d": {
"results": [{
"preferredname": "Bobson A. Dugnutt",
"initials": "BAD",
"jobtitle": "Coolguy",
"office": "New York"
}]
}
};
function loadHeadlineData() {
let res = headlineData.d.results.filter(function(obj) {
return {
"Name": obj.preferredname,
"Initials": obj.initials,
"Title": obj.jobtitle,
"Office": obj.office
}
})
// console.log(res)
$(".headline-cont,h1").append(JSON.stringify(res));
}
loadHeadlineData();
//console.log(headlineData)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="headline-cont h1"></div>