我需要比较两个数组,当记录匹配时,再将记录的记录保存到另一个数组中
Array 1[ { "phId": 10, "value": "[PACKNAME]" }, { "phId": 11, "value": "[PACKTYPE]" }, { "phId": 12, "value": "[BALANCE]" }, { "phId": 17, "value": "[DURATION]" } ] Array 2[ "[PACKNAME]", "[BALANCE]" ]Matched Record Saved Array[ { "phId": 10, "value": "[PACKNAME]" }, { "phId": 12, "value": "[BALANCE]" } ]
如何使用javascript实现此方法。
我可以使用下面的代码进行匹配并将数组保存为相同类型的数组,但是我无法执行上述方案。
let firstArray = ["One", "Two", "Three", "Four", "Five"];let secondArray = ["Three", "Four"];let map = {};firstArray.forEach(i => map[i] = false);secondArray.forEach(i => map[i] === false && (map[i] = true));let jsonArray = Object.keys(map).map(k => ({ name: k, matched: map[k] }))
这是一个简单的用filter
例:
let array1 = [ { "phId": 10, "value": "[PACKNAME]" }, { "phId": 11, "value": "[PACKTYPE]" }, { "phId": 12, "value": "[BALANCE]" }, { "phId": 17, "value": "[DURATION]" } ];let array2 = [ "[PACKNAME]", "[BALANCE]" ];let array3 = array1.filter((el) => array2.includes(el.value));console.log(array3);
用 filter
const arr_one = [ { "phId": 10, "value": "[PACKNAME]" }, { "phId": 11, "value": "[PACKTYPE]" }, { "phId": 12, "value": "[BALANCE]" }, { "phId": 17, "value": "[DURATION]" } ] const arr_two = [ "[PACKNAME]", "[BALANCE]" ]const matched = arr_one.filter( ( item ) => arr_two.includes( item.value ))console.log(matched)/* Matched Record Saved Array [ { "phId": 10, "value": "[PACKNAME]" }, { "phId": 12, "value": "[BALANCE]" } ] */
如果我正确理解了您要执行的操作:您可以仅对第一个数组中value
存在于第二个数组中的元素进行过滤,如下所示:
const firstArray = [ { "phId": 10, "value": "[PACKNAME]" }, { "phId": 11, "value": "[PACKTYPE]" }, { "phId": 12, "value": "[BALANCE]" }, { "phId": 17, "value": "[DURATION]" }] const secondArray = [ "[PACKNAME]", "[BALANCE]" ]const matchedArray = firstArray.filter(({ value }) => secondArray.includes(value))
您不想要所有物品=您不想要map
。
您需要一些符合条件的物品=您想要filter
。
试试这个:
array1.filter(item=>array2.includes(item.value))
array1=[ { "phId": 10, "value": "[PACKNAME]" }, { "phId": 11, "value": "[PACKTYPE]" }, { "phId": 12, "value": "[BALANCE]" }, { "phId": 17, "value": "[DURATION]" } ] array2=[ "[PACKNAME]", "[BALANCE]" ]res = array1.filter(o => array2.includes(o.value))console.log(res)