简体   繁体   English

从第二个数组中存在的第一个数组中删除值

[英]Remove value from first array that exists in the second array

I have this variable: 我有这个变量:

var first = [{name: "john", key: "1"}, 
             {name: "george", key: "3"}, 
             {name: "paul", key: "2"},
             {name: "ringo", key: "4"}];

var second = [{key: "2"}, 
              {key: "4"}, 
              {key: "3"}]

I am trying to create a new object that omits value that is missing at second , in this case, name: "john" : 我试图创建一个新对象,该对象忽略了second缺少的值,在这种情况下, name: "john"

var third = [{name: "george", key: "3"}, 
             {name: "paul", key: "2"},
             {name: "ringo", key: "4"}];

Here's the code I tried: 这是我尝试的代码:

var third = first.map(obj => {
    var retVal = {};
    retVal["name"] = obj.name;
    retVal["key"] = obj.key;
    return retVal;
});

This code adds all and becomes: 此代码将所有内容相加并变为:

var third = [{name: "john", key: "1"}, 
             {name: "george", key: "3"}, 
             {name: "paul", key: "2"},
             {name: "ringo", key: "4"}];

, but can't figure out the restriction that wouldn't add the one I want to omit. ,但无法找出不会增加我要忽略的限制。

Please note, that regular loop is not a deal, it has to be with .map . 请注意,常规循环不是问题,必须使用.map

You can use the functions filter , map and includes as follow: 您可以使用功能filtermapincludes如下:

 var first = [{name: "john", key: "1"}, {name: "george", key: "3"}, {name: "paul", key: "2"},{name: "ringo", key: "4"}], second = [{key: "2"}, {key: "4"}, {key: "3"}], keys = second.map(o => o.key), result = first.filter(o => keys.includes(o.key)); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TS 2 arrays,如果第一个数组中的项目存在于第二个数组中,则 append 到第二个数组的开头 - TS 2 arrays, if item from first array exists in second array then append to start of second array 如果 javascript 中的数组中存在某个值,则从 Array 中删除一个数组 - Remove an array from an Array if a certain value exists in the array in javascript JavaScript如果数组2中存在值,则从数组1中删除项目 - Javascript Remove Item from array 1 if value exists in array 2 如果其他数组中存在值,则JavaScript从数组中删除对象 - JavaScript remove object from array if value exists in other array 如何将第一个数组中索引[0]的值赋给第二个数组中的索引[0]? - How to assign a value from index[0] in first array to index[0] in second array? Javascript 比较两个对象数组并根据第二个数组从第一个数组中删除元素并删除第一次出现的记录 - Javascript comparing two array of objects and remove the elements from first array based on second array and remove first occurence records 如果键值已经存在,如何从数组中删除对象 - 打字稿 - How to remove object from an array if key value already exists - typescript 如果 object 参数值已存在于 JavaScript 中,则从数组中删除 object - Remove object from array if object parameter value already exists in JavaScript 如果不在第二个阵列中,则从一个阵列中删除项目 - Remove items from one array if not in the second array javascript:从第二个数组中的数组中删除值 - javascript: remove values from an array that are in a second array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM