[英]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: 您可以使用功能
filter
, map
和includes
如下:
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.