[英]What is the proper way of forming required data object from an http response
我從 api 調用中接收到某個數組,並且我需要從中形成一個對象數組。 這是我從服務器接收的對象數組
[
{x:10,id:1,y:30},
{x:10,id:2,y:50},
{x:11,id:1,y:20},
{x:11,id:2,y:70},
{x:12,id:1,y:80},
{x:12,id:2,y:90}
]
...我需要將其轉換為:
[
{x:10,id1:30,id2:50},
{x:11,id2:20,id2:70},
{x:12,id3:80,id2:90}
]
基本上將y
部分存儲在各自的 object 中
我試圖生成所需的 object,但我不得不使用太多循環。 有沒有更簡單或更准確的方法?
你可以試試這個
let arr=[ {x:10,id:1,y:30},
{x:10,id:2,y:50},
{x:11,id:1,y:20},
{x:11,id:2,y:70},
{x:12,id:1,y:80},
{x:12,id:2,y:90}
]
let ans=[];
arr.forEach(o=>{
if( !ans.find(i=>o.x===i.x)){
let id2=arr.find(item=>(item.x===o.x && item.id!==o.id));
if(id2)
ans.push({x:o.x,id1:o.y,id2:id2.y});
}
});
console.log(ans);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.