假设我有下面的数据,我正在尝试确定如何删除具有notice_id = 3的消息对象。我无法弄清楚如何删除单个消息。有可能吗?
var newMockData = [
{"date": "JAN 18 2016",
"messages": [{
"notice_id": "1",
"notice_title": "Bad news",
"notice_text": "Server is down!",
"start_date": "2016-09-18T04:00:00Z"
},
{
"notice_id": "2",
"notice_title": "Weekly Reminder",
"notice_text": "Please read the assignment!",
"start_date": "2016-09-18T04:00:00Z"
}]
},
{"date": "JAN 19 2016",
"messages": [{
"notice_id": "3",
"notice_title": "Sweet",
"notice_text": "This morning, the new edition of our blog hit stands!",
"start_date": "2016-09-19T04:00:00Z"
},
{
"notice_id": "4",
"notice_title": "Yeah",
"notice_text": "This is pretty cool",
"start_date": "2016-09-19T04:00:00Z"
}]
}
]
答案 0 :(得分:0)
您可以循环遍历数组并在messages
数组上使用remove:
_.forEach(newMockData, function (el) {
_.remove(el.messages, { notice_id: '3'});
});
var newMockData = [{
"date": "JAN 18 2016",
"messages": [{
"notice_id": "1",
"notice_title": "Bad news",
"notice_text": "Server is down!",
"start_date": "2016-09-18T04:00:00Z"
},{
"notice_id": "2",
"notice_title": "Weekly Reminder",
"notice_text": "Please read the assignment!",
"start_date": "2016-09-18T04:00:00Z"
}]
},{
"date": "JAN 19 2016",
"messages": [{
"notice_id": "3",
"notice_title": "Sweet",
"notice_text": "This morning, the new edition of our blog hit stands!",
"start_date": "2016-09-19T04:00:00Z"
},{
"notice_id": "4",
"notice_title": "Yeah",
"notice_text": "This is pretty cool",
"start_date": "2016-09-19T04:00:00Z"
}]
}];
_.forEach(newMockData, function (el) {
_.remove(el.messages, { notice_id: '3' });
});
console.log(newMockData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.1/lodash.min.js"></script>
答案 1 :(得分:0)
你可以使用JS map()
和filter()
(或者他们的lodash等价物)创建一个没有消息的新数组,而不会改变原始数据:
function removeMessage(data, messageId) {
return data.map(function(item) {
return item.messages.filter(function(message) {
return message.notice_id !== messageId;
});
});
}
var newMockData = [{
"date": "JAN 18 2016",
"messages": [{
"notice_id": "1",
"notice_title": "Bad news",
"notice_text": "Server is down!",
"start_date": "2016-09-18T04:00:00Z"
}, {
"notice_id": "2",
"notice_title": "Weekly Reminder",
"notice_text": "Please read the assignment!",
"start_date": "2016-09-18T04:00:00Z"
}]
}, {
"date": "JAN 19 2016",
"messages": [{
"notice_id": "3",
"notice_title": "Sweet",
"notice_text": "This morning, the new edition of our blog hit stands!",
"start_date": "2016-09-19T04:00:00Z"
}, {
"notice_id": "4",
"notice_title": "Yeah",
"notice_text": "This is pretty cool",
"start_date": "2016-09-19T04:00:00Z"
}]
}];
var result = removeMessage(newMockData, '3');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.1/lodash.min.js"></script>