美文网首页
从对象数组中返回一个筛选后的对象数组

从对象数组中返回一个筛选后的对象数组

作者: 可乐杯杯hh | 来源:发表于2018-09-16 20:52 被阅读0次

这还是一个数组过滤

把字符和数字元素换成了对象

这是要求


whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }) should return [{ first: "Tybalt", last: "Capulet" }].
Passed
whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 }) should return [{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }].
Passed
whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }) should return [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }].
Passed
whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 }) should return [{ "apple": 1, "bat": 2, "cookie": 2 }].
Passed
whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 }) should return [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }].
Passed
whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3}) should return []

这是解决方案


function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];
  // Only change code below this line
  let sourceKeys = Object.keys(source);
  for (let i = 0; i < collection.length; i++)
  { 
    var count = 0;//注意这个计数器,如果放在里面一个循环则没有效果
    for (let j = 0; j < sourceKeys.length; j++)
    {
      
      for (let x in collection[i])
      {
        if (x === sourceKeys[j] && collection[i][x] === source[sourceKeys[j]])
        {
          count++;
        }
      } 
    }
    if (count === sourceKeys.length)
    {
      arr.push(collection[i]);
    }
  }
  // Only change code above this line
  return arr;
}

whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

相关文章

  • 从对象数组中返回一个筛选后的对象数组

    这还是一个数组过滤 把字符和数字元素换成了对象 这是要求 这是解决方案

  • js 数组操作合集(主要针对对象数组)

    1,根据对象中元素 查找对象数组中对应的元素 2,删除数组中指定对象的元素 并返回删除后的数组 3,js数组实现权...

  • keys

    定义和用法 keys() 方法用于从数组创建一个包含数组键的可迭代对象。 如果对象是数组返回 true,否则返回 ...

  • JS 函数封装

    返回数组或对象的长度 返回数组中的非假值组成一个新数组 返回数组中任意一个元素 数组去重复

  • js中for in、for of、forEach

    遍历数组 for in返回数组的索引 for of返回数组的元素 遍历对象 for in返回对象的键 for of...

  • iOS杂碎2

    NSPredicate用法之一: 数组元素为对象时,通过对象的某个属性快速筛选出数组中的对象 关于NSPredic...

  • swift 一个数组分成多个数组

    把后台返回的数组分成多个数组,如下的例子是,把后台返回的数组分成前面是每个数组8个对象,剩下的对象放在一个数组中

  • js.array api 常用

    function:Array.from 函数从类似数组的对象或可迭代的对象返回一个数组。 Array.isArra...

  • es6常用数组方法

    .map() 返回一个 由数组对象中某个属性值 所组成的数组 .filter() 返回一个由 原数组中符合某些条件...

  • promise.all(),ajax,js 并发请求

    paths.map 返回经过https拼接的url后返回新的数组,新的数组map 返回的是promise对象的数组...

网友评论

      本文标题:从对象数组中返回一个筛选后的对象数组

      本文链接:https://www.haomeiwen.com/subject/pxwfnftx.html