我們想從 JSON 中洗掉重復的節點。如果trait_type值相同,該節點將被洗掉
這是JSON
[
{
"trait_type": "Background",
"value": "Yellow"
},
{
"trait_type": "A",
"value": "None"
},
{
"trait_type": "B",
"value": "Male Body Grey Color"
},
{
"trait_type": "A",
"value": "Outfit"
}
]
最終的 JSON 應該是這樣的。
[
{
"trait_type": "Background",
"value": "Yellow"
},
{
"trait_type": "A",
"value": "None"
},
{
"trait_type": "B",
"value": "Male Body Grey Color"
}
]
請幫忙
謝謝
uj5u.com熱心網友回復:
你可以試試這樣的
let data = [{
"trait_type": "Background",
"value": "Yellow"
},
{
"trait_type": "A",
"value": "None"
},
{
"trait_type": "B",
"value": "Male Body Grey Color"
},
{
"trait_type": "A",
"value": "Outfit"
}
];
const uniqueIDs = new Set();
let uniqueData = data.filter(x => {
const duplicate = uniqueIDs.has(x.trait_type);
uniqueIDs.add(x.trait_type);
return !duplicate;
});
console.log(uniqueData);
uj5u.com熱心網友回復:
所以我猜你的 json 是一個 javascript 陣列,否則使用 JSON.parse 來轉換它。
所以你想要的是洗掉陣列中的雙值并且公平地說有很多事情要做,我個人使用 Set 來做到這一點,但為了“初學者友好”,我將使用一個大的臨時物件來存盤價值和通過參考檢索它們
const data = [
{
"trait_type": "Background",
"value": "Yellow"
},
{
"trait_type": "A",
"value": "None"
}]
const tmpObject = {};
data.forEach((d) => {
if (!tmpObject[d?.trait_type]) {
tmpObject[d.trait_type] = d; // we only push data indide the object if the keys does not exist and the keys is the value you want to be unique so once you have a value matching we will not add the next data (with same trait_type) inside the object
}
});
// now build the new array is like
theArrayYouWant = [];
Object.keys(tmpObject).forEach((d) => {
theArrayYouWant.push(tmpObject[d]);
});
uj5u.com熱心網友回復:
這個純函式應該做:
function filterUnique(data){
const unique = {};
data.forEach(el => {
unique[el.trait_type] = el;
});
return Object.values(unique);
}
//
const filteredJSON = filterUnique(json);
uj5u.com熱心網友回復:
嘗試這個
var noDuplicatesArr = origArr.filter((v,i,a)=>a.findIndex(v2=>(v2.trait_type===v.trait_type))===i);
console.log(noDuplicatesArr);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/451886.html
標籤:javascript 节点.js json
上一篇:JavaScript的查找功能
下一篇:如何為多個欄位為空顯示單個警報?
