[英]How can i merge objects with the same id
见图片:
Console.log 图像 POST ID
我试图用每个修复它,但我不知道如何更进一步。
看我的代码:
jQuery(document).ready(function($) {
var data, exampleData, , exampleType, exampleStatus, exampleKey, exampleValue;
data = {
'action': 'ajax'
};
jQuery.post(ajaxurl, data, function(response) {
exampleData = jQuery.parseJSON(response);
jQuery.each(exampleData, function(index, value) {
exampleID = value.post_id;
exampleType = value.post_type;
exampleStatus = value.post_status;
exampleKey = value.meta_key;
exampleValue = value.meta_value;
if (exampleType == 'type' && exampleStatus === 'publish' && exampleID === values.ID) {
console.log(exampleValue);
}
});
});
});
我想合并所有具有相同 ID 的 ID 并将其作为数组或对象返回。
这可能需要进行一些调整,具体取决于您希望返回的数据结构的外观——“数组或对象”留下了很多选项——但应该足以演示一种方法来做到这一点:
exampleData = [ {meta_id: "6098", post_id: "2283"}, {meta_id: "6099", post_id: "2283"}, {meta_id: "6100", post_id: "2283"}, {meta_id: "6101", post_id: "2283"}, {meta_id: "6102", post_id: "2283"}, {meta_id: "6103", post_id: "2283"}, {meta_id: "6104", post_id: "2284"}, {meta_id: "6105", post_id: "2284"}, {meta_id: "6106", post_id: "2285"}, {meta_id: "6107", post_id: "2285"} ] const reducer = (acc, cur)=>{ acc[cur.post_id] = acc[cur.post_id] || []; // start an array for this ID if we don't already have one acc[cur.post_id].push(cur) // push the current object onto this id's array return acc; } let output = exampleData.reduce(reducer, {}) console.log(output);
请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
var mylist= [
{ meta_id: '6097', post_id: '2055' },
{ meta_id: '6098', post_id: '2056' },
{ meta_id: '6099', post_id: '2057' },
{ meta_id: '6099', post_id: '2077' }
];
function DelDoublonsBy(arObjets, the_prop){
var arr_prop_as_key=[];
return arObjets.reduce(function (list_previtems, obj) {
var the_key = obj[the_prop];
if(!arr_prop_as_key[the_key]){
arr_prop_as_key[the_key] = "key exist";
list_previtems.push(obj);
}
return list_previtems;
}, []);
}
var mylist_unique_By_metaid = DelDoublonsBy( mylist, "meta_id");
console.log("mylist_unique_By_metaid : "+mylist_unique_By_metaid);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.