用Js

时间:2017-09-19 12:58:30

标签: javascript arrays json object

javascript上的初学者,我有一个问题是转移我的对象数组的值" objects1"在JSON中新对象的对象" objects2",总是在JSON中。

objects1 = [
{"name" : "Jake" , "class" : "D"},
{"name" : "Maria" , "class" : "C"},
{"name" : "Donald" , "class" : "C"},
{"name" : "Mike" , "class" : "E"},
{"name" : "Eva" , "class" : "C"}
]

objects2 = [
{"class" : "D" , "total" : "1"},
{"class" : "C" , "total" : "3"},
{"class" : "E" , "total" : "1"}
]

我此刻只设法删除了重复内容......

 var cache = {};
objects2 = objects1.filter(function(elem,index,array){
                return cache[elem.currency_name]?0:cache[elem.currency_name]=1;
});

3 个答案:

答案 0 :(得分:2)

您可以将Object.values()reduce()一起使用。

var data = [
{"name" : "Jake" , "class" : "D"},
{"name" : "Maria" , "class" : "C"},
{"name" : "Donald" , "class" : "C"},
{"name" : "Mike" , "class" : "E"},
{"name" : "Eva" , "class" : "C"}
]

var result = Object.values(data.reduce(function(r, e) {
  if(!r[e.class]) r[e.class] = {class : e.class , total: 0}
  r[e.class].total += 1;
  return r;
}, {}))

console.log(result)

答案 1 :(得分:1)

Array#reduce与辅助对象一起使用以创建新数组:



var arr1 = [{"name":"Jake","class":"D"},{"name":"Maria","class":"C"},{"name":"Donald","class":"C"},{"name":"Mike","class":"E"},{"name":"Eva","class":"C"}];

var helper = Object.create(null); // create an empty object
var result = arr1.reduce(function(r, o) {
  var item = helper[o.class]; // get the item from the helper via the class
  if(!item) { // if the item doesn't exist
    item = { class: o.class, total: 0 }; // create a new item
    
    helper[o.class] = item; // add it to the helper
    r.push(item); // push to the result array
  }
  
  item.total++; // increment the total
  
  return r;
}, []);

console.log(result);




使用Map和数组的ES6版本#reduce:



const arr1 = [{"name":"Jake","class":"D"},{"name":"Maria","class":"C"},{"name":"Donald","class":"C"},{"name":"Mike","class":"E"},{"name":"Eva","class":"C"}];

const result = [...arr1.reduce((map, o) => {
  const item = map.get(o.class) || { class: o.class, total: 0 }; // get the item from the map or create a new one
  
  item.total++; // increment the total
  
  return map.set(o.class, item); // set the item and return the map
}, new Map()).values()]; // convert the map to values iterator, and spread to get an array

console.log(result);




答案 2 :(得分:0)

您可以使用Set:

var objects1 = [
    {"name" : "Jake" , "class" : "D"},
    {"name" : "Maria" , "class" : "C"},
    {"name" : "Donald" , "class" : "C"},
    {"name" : "Mike" , "class" : "E"},
    {"name" : "Eva" , "class" : "C"}
];
var classes = new Set(objects1.map(obj => obj.class));
var objects2 = [];
classes.forEach(cl => {
    var obj = { class: cl, total: objects1.filter(it => it.class === cl).length };
    objects2.push(obj);
});
console.log(objects2);