使用javascript中的值数组过滤深度嵌套的对象数组
我想知道如何用javascript中的值数组过滤深度嵌套的对象数组(动态) 注意,使用javascript中的值数组过滤深度嵌套的对象数组,javascript,html,arrays,object,Javascript,Html,Arrays,Object,我想知道如何用javascript中的值数组过滤深度嵌套的对象数组(动态) 注意,Obj是动态的 var result = getData(obj); getData(obj){ var getcn = obj.map(e=>e.cn); var tot = obj.filter(e=>getcn.includes(e.cn)); } 预期产出: [{ "cn": "SG", "total": 2 // length of cn `SG` },{ "cn":
Obj
是动态的
var result = getData(obj);
getData(obj){
var getcn = obj.map(e=>e.cn);
var tot = obj.filter(e=>getcn.includes(e.cn));
}
预期产出:
[{
"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”}];
让res=对象减少((acc,cur)=>{
if(acc.some(obj=>obj.cn==cur.cn)){
返回acc.map(obj=>obj.cn===cur.cn?{cn:obj.cn,total:obj.total+1}:obj)
}
返回acc.concat({cn:cur.cn,总计:1})
},[])
console.log(res)
var obj=[
{
“cn”:“SG”,
“金额”:“30”
},
{
“cn”:“SG”,
“金额”:“40”
},
{
“cn”:“我的”,
“金额”:“100”
},
{
“cn”:“TH”,
“金额”:“40”
}
]
函数getData(obj){
设频率={},结果=[];
对象映射((项目)=>{
如果(item.cn频率)
频率[item.cn]++;
其他的
频率[item.cn]=1;
})
for(让对象的[键,值]输入(频率))
push({cn:key,total:value})
返回结果;
}
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;
}, []);
}
//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;
}, []);
}