фильтровать массив вложенных объектов с массивом значений в javascript - PullRequest
0 голосов
/ 14 января 2020

Мне бы хотелось, как отфильтровать массив вложенных объектов (Dynami c) с массивом значений в javascript Обратите внимание, Obj это Dynami c.

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
}]

Ответы [ 3 ]

0 голосов
/ 14 января 2020

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))
0 голосов
/ 14 января 2020

Я не уверен, что вы подразумеваете под 'obj is dynamici c', но в основном вам нужно go просмотреть массив значений и добавить каждое значение в новый массив. Однако, если значение уже существует в этом новом массиве, вы просто увеличиваете его общее значение на единицу.

//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;
  }, []);
}
0 голосов
/ 14 января 2020

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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...