JavaScript - 使用唯一属性标识对象

时间:2016-05-07 17:31:37

标签: javascript object properties

我已设法识别计数属性中的最高数字但是我想记录与该数字相关联的对象,即记录具有最高计数的对象。我该怎么做呢?

var objects = {

    object1: {username: 'mark', count: 3},
    object2: {username: 'dave', count: 5},
    object3: {username: 'lucy', count: 2},
};

var maxBap = Math.max.apply(Math,objects.map(function(o){return o.count;}));
console.log(maxBap);

由于

3 个答案:

答案 0 :(得分:2)

使用.reduce()代替 public function updateAction(Request $request) { $em = $this->getDoctrine()->getManager(); $idEvent=$request->get('Eventid'); $Start=$request->get('Start'); $Stop=$request->get('End'); $events= $em->getRepository('AppBundle:Event')->find($idEvent); $events->setStart($Start); $events->setEnd($Stop); $em->flush(); if($request->isXmlHttpRequest()) { $json = json_encode([ 'id' => $events->getId() ]); return new Response($json); } } ,以获得所需的目标。

这里我将返回结果对象的键。如果您愿意,可以直接返回对象。

.map()
var objects = {
    object1: {username: 'mark', count: 3},
    object2: {username: 'dave', count: 5},
    object3: {username: 'lucy', count: 2},
};

var res = Object.keys(objects).reduce(function(resKey, key) {
  return objects[resKey].count > objects[key].count ? resKey : key
})

document.querySelector("pre").textContent = res + ": " +
  JSON.stringify(objects[res], null, 4);

如果<pre></pre>是一个数组,您仍然可以使用objects,而不是.reduce()。这会直接返回对象,这是第一个解决方案中提到的。

Object.keys()
var objects = [
    {username: 'mark', count: 3},
    {username: 'dave', count: 5},
    {username: 'lucy', count: 2},
];

var res = objects.reduce(function(resObj, obj) {
  return resObj.count > obj.count ? resObj : obj
})

document.querySelector("pre").textContent =
  JSON.stringify(res, null, 4);

答案 1 :(得分:1)

您可以使用.reduce代替.map

const objects = [
  { username: 'mark', count: 3 },
  { username: 'dave', count: 5 },
  { username: 'lucy', count: 2 },
]

const max = objects.reduce((acc, obj) => (
  obj.count > acc.count ? obj : acc
))

console.log(max)

答案 2 :(得分:1)

您可以先找到max的计数,然后找到具有该计数的对象

var objects = {
    object1: {username: 'mark', count: 3},
    object2: {username: 'dave', count: 5},
    object3: {username: 'lucy', count: 2},
}, result = null;

var max = Math.max.apply(null, Object.keys(objects).map(e => {return objects[e].count}));

for (var obj in objects) {
  if (objects[obj].count == max) result = objects[obj];
}

console.log(result)