![](/img/trans.png)
[英]JavaScript - Filter Object from criteria array, by deeply nested object key?
[英]filter through deeply nested object array with array of values in javascript
我想如何使用javascript中的值數組過濾深層嵌套的對象數組(動態)注意, Obj
是動態的。
var result = getData(obj);
getData(obj){
var getcn = obj.map(e=>e.cn);
var tot = obj.filter(e=>getcn.includes(e.cn));
}
//input
var obj = [{
"cn": "SG",
"amt": "30"
},{
"cn": "SG",
"amt": "40"
},{
"cn": "MY",
"amt": "100"
},{
"cn": "TH",
"amt": "40"
}]
預期輸出:
[{
"cn": "SG",
"total": 2 // length of cn `SG`
},{
"cn": "MY",
"total": 1
},{
"cn": "TH",
"total": 1
}]
var obj=[{cn:"SG",amt:"30"},{cn:"SG",amt:"40"},{cn:"MY",amt:"100"},{cn:"TH",amt:"40"}]; let res = obj.reduce((acc,cur) => { if(acc.some(obj => obj.cn === cur.cn)){ return acc.map(obj => obj.cn === cur.cn ? {cn: obj.cn, total: obj.total + 1} : obj) } return acc.concat({cn: cur.cn, total: 1}) },[]) console.log(res)
var obj = [ { "cn": "SG", "amt": "30" }, { "cn": "SG", "amt": "40" }, { "cn": "MY", "amt": "100" }, { "cn": "TH", "amt": "40" } ] function getData(obj){ let frequency = {}, result = []; obj.map((item)=>{ if(item.cn in frequency) frequency[item.cn]++; else frequency[item.cn] = 1; }) for(let [key,value] of Object.entries(frequency)) result.push({cn:key,total:value}) return result; } console.log(getData(obj))
我不確定你所說的“obj 是動態的”是什么意思,但基本上,你需要遍歷一個值數組並將每個值添加到一個新數組中。 但是,如果該值已存在於這個新數組中,則只需將其總數增加 1。
//input
var input = [{
"cn": "SG",
"amt": "30"
},{
"cn": "SG",
"amt": "40"
},{
"cn": "MY",
"amt": "100"
},{
"cn": "TH",
"amt": "40"
}];
const getData = (data) => {
const entryIndexByCn = {}; // store index of the value in the new array,
// so we could then increase total by 1
// in case the value was already added
return data.reduce((memo, entry) => {
// get index of the value in the new array
const entryIndex = entryIndexByCn[entry.cn];
// if value is in the new array, increase total by 1
if (entryIndex !== undefined) {
memo[entryIndex].total += 1;
} else {
// if not, record index of the value to
// address it later if we meet the value again
// to be able to increase its total
entryIndexByCn[entry.cn] = memo.length;
// and add new value to the new array
memo.push({
cn: entry.cn,
total: 1
});
}
return memo;
}, []);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.