如何合并具有相同ID的对象

时间:2019-04-14 15:42:36

标签: jquery object merge id

查看图片:

Console.log映像POST ID

Console.log Image POST ID's

我已经尝试对每个问题进行修复,但是我不知道该怎么做。

查看我的代码:

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,并将其作为数组或对象返回。

2 个答案:

答案 0 :(得分:1)

这可能需要进行一些调整,具体取决于您希望返回的数据结构是什么样子-“数组或对象”留下了很多选择-但应该足以演示执行此操作的一种方法:

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

答案 1 :(得分:0)

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);