根据另一个对象数组过滤对象数组并返回合并的数组

时间:2018-08-22 09:56:29

标签: javascript arrays object filter

我有一个这样的对象数组:

phoneContacts= [
{
  firstName: "aaaa", 
  lasttName: "aaaa", 
  phoneNumbers: [{id: "1", label: "mobile", number: "09121111111"},{id: "1", label: "home", number: "02188888888"}]
},
{
  firstName: "bbbb", 
  lasttName: "bbbb", 
  phoneNumbers: [{id: "1", label: "mobile", number: "09122222222"},{id: "1", label: "home", number: "02177777777"}],
},
...]

我想用这样的数组过滤它:

registeredUsers= [
{
  ID: 1, 
  CellPhone: "09123333333"
},
{
  ID: 2, 
  CellPhone: "09121111111"
},
...]

并返回:

contactsMergerdWithID= [
{
  ID: 1,
  firstName: "aaaa", 
  lasttName: "aaaa", 
  phoneNumbers: [{id: "1", label: "mobile", number: "09121111111"},{id: "1", label: "home", number: "02188888888"}]
},
{
  ID: 0,            // or without ID
  firstName: "bbbb", 
  lasttName: "bbbb", 
  phoneNumbers: [{id: "1", label: "mobile", number: "09122222222"},{id: "1", label: "home", number: "02177777777"}]
},
...]

如果任何移动电话号码与第二个数组中的CellPhone匹配,我想返回第二个数组中具有匹配ID字段的第一个数组。 我该怎么办?

2 个答案:

答案 0 :(得分:1)

import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

n = 100
x = np.linspace(0,2,n)
y1 = np.sin(2*np.pi*x)
y2 = np.sin(4*np.pi*x)
y3 = np.sin(6*np.pi*x)

df = pd.DataFrame(np.c_[y1, y2, y3], index=x)

ax = sns.lineplot(data=df)
plt.show()

答案 1 :(得分:0)

您可以使用地图查找并解构结果对象

const mapped = phoneContacts.map(e => {
  return {...e, ...{id: (registeredUsers.find(r => r.CellPhone === (e.phoneNumbers.find(p => p.label === 'mobile') || {number: -1}).number ) || {ID: 0}).ID}} ;
});
console.log(mapped);
<script>
const phoneContacts= [
  {
    firstName: "aaaa",
    lasttName: "aaaa",
    phoneNumbers: [{id: "1", label: "mobile", number: "09121111111"},{id: "1", label: "home", number: "02188888888"}]
  },
  {
    firstName: "bbbb",
    lasttName: "bbbb",
    phoneNumbers: [{id: "1", label: "mobile", number: "09122222222"},{id: "1", label: "home", number: "02177777777"}],
  },
]

const registeredUsers= [
  {
    ID: 1,
    CellPhone: "09123333333"
  },
  {
    ID: 2,
    CellPhone: "09121111111"
  },
  ];

</script>