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

问题描述 投票:0回答:2

见图:

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

jquery object merge id
2个回答
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


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);
© www.soinside.com 2019 - 2024. All rights reserved.