簡體   English   中英

如何合並具有相同 id 的對象

[英]How can i merge objects with the same id

見圖片:

Console.log 圖像 POST 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM