我有这个变量:
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"}]
我正在尝试创建一个新对象,忽略second
所缺少的值,在本例中为name: "john"
:
var third = [{name: "george", key: "3"},
{name: "paul", key: "2"},
{name: "ringo", key: "4"}];
这是我尝试过的代码:
var third = first.map(obj => {
var retVal = {};
retVal["name"] = obj.name;
retVal["key"] = obj.key;
return retVal;
});
此代码添加全部并变为:
var third = [{name: "john", key: "1"},
{name: "george", key: "3"},
{name: "paul", key: "2"},
{name: "ringo", key: "4"}];
,但无法找出不会添加我想省略的限制。
请注意,常规循环不是一个交易,它必须与.map
。
答案 0 :(得分:2)
您可以使用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; }