我有一个来自API的JSON,API的响应是声明任务是否已经完成,
JSON的例子:
[ { Name: 'Pre Operation', Checked: false },
{ Name: 'Operation', Checked: false },
{ Name: 'Post Operation', Checked: false } ]
如何将JSON更新为:
[ { Name: 'Pre Operation', Checked: true},
{ Name: 'Operation', Checked: false },
{ Name: 'Post Operation', Checked: false } ]
我尝试过使用此代码:
var output = jsonResult.map((item)=>{
if(item.Checked == true){
item.Checked === false
}
return item
})
但是JSON没有改变,我害怕item.Checked === false
会影响item.Checked
值true
的所有[ { Name: 'Pre Operation', Checked: true},
{ Name: 'Operation', Checked: false },
{ Name: 'Post Operation', Checked: false } ]
如果我有这样的API响应:
[ { Name: 'Pre Operation', Checked: true},
{ Name: 'Operation', Checked: true},
{ Name: 'Post Operation', Checked: false } ]
我需要将JSON更新为:
jQuery(document).ready(function($) {
// JS to submit ajax for load more button
$(document).on('click', '#load-more-posts', function(e) {
$('#load-more-posts-error').hide();
var previouspaged = $(this).attr('data-paged');
var currentpaged = parseInt(previouspaged) + 1;
jQuery.ajax({
type: 'POST',
url: wp_ajax_url,
data: {
action: 'load_more_posts',
paged: currentpaged,
context: $(this).attr('data-context'),
query: load_more_data.query,
nonce: $('#load-more-posts-nonce').val(),
},
dataType: 'html'
})
.done(function(response) {
if (response) {
$('#load-more-posts-area-wrapper').append(response);
if (currentpaged > parseInt($('#load-more-posts').attr('data-max-pages'))) {
$('#load-more-posts').hide();
} else {
$('#load-more-posts').attr('data-paged', currentpaged);
}
} else {
$('#load-more-posts').hide();
$('#load-more-posts-error').show();
}
});
e.preventDefault();
});
});
任何人都可以帮助我如何实现我的目标?
答案 0 :(得分:3)
var arr = [ { Name: 'Pre Operation', Checked: false }, { Name: 'Operation', Checked: false }, { Name: 'Post Operation', Checked: false } ];
function updateStatus(){
var result = arr.find(({Checked}) => !Checked);
if(result) result.Checked = true;
}
updateStatus(); console.log(arr); // first is updated
updateStatus(); console.log(arr); // second is updated
updateStatus(); console.log(arr); // third is updated
updateStatus(); console.log(arr); // no update

答案 1 :(得分:0)
不确定我是否误解了这个问题,但你肯定可以......
jsonResult[0].Checked = true;
编辑..如果你想减少无情......
jsonResult.some((item) => { if (item.Name = 'Pre Operation') { item.Checked = true; return true; })
array.prototype.some是一种在你完成所需工作时存在循环的好方法 - 一旦真实'返回它将停止循环。