首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将具有不同属性名称的对象数组拆分为一个对象,并根据给定的名称将它们分开。

将具有不同属性名称的对象数组拆分为一个对象,并根据给定的名称将它们分开。
EN

Stack Overflow用户
提问于 2022-06-23 17:16:24
回答 3查看 157关注 0票数 2

我有一个包含对象的数组。现在,我希望将数组切片到一个新对象中,该对象只包含与某个属性名称匹配的对象,并按该属性名称分组。问题是,我的属性名称在它们之间是不同的。名称和ID通过对象数组重复,但是在新对象中,它应该只包含一次ID和名称。

原始数组如下所示:

代码语言:javascript
复制
let personArray = [
    {
        id_dentist: 1,
        dentist_name: 'John',
        id_secretary: 6,
        secretary_name: 'Paul',
        id_security: 3,
        security_name: 'Carl'
    },
    {
        id_dentist: 2,
        dentist_name: 'Lisa',
        id_secretary: 9,
        secretary_name: 'Beth',
        id_security: 5,
        security_name: 'Monica'
    },
    {
        id_dentist: 1,
        dentist_name: 'John',
        id_secretary: 6,
        secretary_name: 'Paul',
        id_security: 3,
        security_name: 'Carl'
    }
];

新对象应该如下所示:

代码语言:javascript
复制
let personObject = {
    dentist: [
        { id_dentist: 1, dentist_name: 'John' },
        { id_dentist: 2, dentist_name: 'Lisa' },
    ],
    secretary: [
        { id_secretary: 6, secretary_name: 'Paul' },
        { id_secretary: 9, secreatary_name: 'Beth' },
    ],
    security: [
        { id_security: 3, security_name: 'Carl' },
        { id_security: 5, security_name: 'Monica' }
    ]
};

我很感激你的帮助。

按照要求,我尝试使用reduce()filter(),但无法使它们分离。以下是代码:

代码语言:javascript
复制
const obj = personArray.reduce((acc, cur) => {
    const key = Object.keys(cur).filter(f => /^id_/.test(f))[0].split('_')[1];
    if (!acc[key]) acc[key] = [];
    acc[key].push(cur);
    return acc;
}, {});

console.log(obj);

关于奇怪的数据结构,我使用SELECT SQL语法从数据库中获取这些数据。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-06-23 18:01:38

给您,这可以进一步增强。

代码语言:javascript
复制
let personArray = [{"id_dentist":1,"dentist_name":"John","id_secretary":6,"secretary_name":"Paul","id_security":3,"security_name":"Carl"},{"id_dentist":2,"dentist_name":"Lisa","id_secretary":9,"secretary_name":"Beth","id_security":5,"security_name":"Monica"},{"id_dentist":1,"dentist_name":"John","id_secretary":6,"secretary_name":"Paul","id_security":3,"security_name":"Carl"}];

const personObject = { dentist: [], secretary: [], security: [] };
const isExist = (arr, id, key) => arr.find(x => x[key] === id);


personArray.reduce((personObj, person) => {
  
  const isDentistExists = isExist(personObj.dentist, person.id_dentist, 'id_dentist');
  
  if (!isDentistExists) {
    personObj.dentist.push({
      id_dentist: person.id_dentist,
      dentist_name: person.dentist_name
    });
  }
  
  const isSecretaryExists = isExist(personObj.secretary, person.id_secretary, 'id_secretary');
  
  if (!isSecretaryExists) {
    personObj.secretary.push({
      id_secretary: person.id_secretary,
      secretary_name: person.secretary_name
    });
  }
  
  const isSecurityExists = isExist(personObj.security, person.id_security, 'id_security');
  
  if (!isSecurityExists) {
    personObj.security.push({
      id_security: person.id_security,
      security_name: person.security_name
    });
  }
  
  return personObj;
}, personObject);

console.log(personObject);

票数 3
EN

Stack Overflow用户

发布于 2022-06-23 18:10:45

这不是一个简单的算法。下面是一个主要是函数的实现,它处理任意数量的ids和名称

代码语言:javascript
复制
let personArray = [
  {
    id_dentist: 1,
    dentist_name: 'John',
    id_secretary: 6,
    secretary_name: 'Paul',
    id_security: 3,
    security_name: 'Carl',
  },
  {
    id_dentist: 2,
    dentist_name: 'Lisa',
    id_secretary: 9,
    secretary_name: 'Beth',
    id_security: 5,
    security_name: 'Monica',
  },
  {
    id_dentist: 1,
    dentist_name: 'John',
    id_secretary: 6,
    secretary_name: 'Paul',
    id_security: 3,
    security_name: 'Carl',
  },
]

const parsed = Object.fromEntries(
  Object.keys(personArray[0])
    .filter(key => key.startsWith('id_'))
    .map(id => {
      const uniqIds = [...new Set(personArray.map(person => person[id]))]
      const [, name] = id.split('_')
      const matchingPeople = uniqIds.map(uniqId => {
        return personArray.find(person => uniqId === person[id])
      })
      return matchingPeople.map(person => ({
        [id]: person[id],
        [`${name}_name`]: person[`${name}_name`],
      }))
    })
    .filter(entry => entry.length > 0)
    .map(groupedPeople => {
      const [name] = Object.keys(groupedPeople[0])
        .find(key => key.includes('_name'))
        .split('_')
      return [name, groupedPeople]
    })
)
console.log(parsed)

票数 1
EN

Stack Overflow用户

发布于 2022-06-23 18:34:28

我可能走了一条类似于“安德鲁”的道路,当然,我也承认,这并不是微不足道的事情。

最好更改SQL选择,以避免接收冗余数据,从而使这些冗长的转换成为必要。

代码语言:javascript
复制
const arr = [
{
    id_dentist: 1,
    dentist_name: 'John',
    id_secretary: 6,
    secretary_name: 'Paul',
    id_security: 3,
    security_name: 'Carl'
},
{
    id_dentist: 2,
    dentist_name: 'Lisa',
    id_secretary: 9,
    secretary_name: 'Beth',
    id_security: 5,
    security_name: 'Monica'
},
{
    id_dentist: 1,
    dentist_name: 'John',
    id_secretary: 6,
    secretary_name: 'Paul',
    id_security: 3,
    security_name: 'Carl'
}
], types=Object.keys(arr[0]).reduce((a,c,k)=>{
 k=c.match(/id_(.*)/);
 if(k) a.push(k[1]);
 return a;
},[]);

const res=Object.entries(arr.reduce((a,c)=>{
 types.forEach((t,id)=>{
  id="id_"+t;
  a[t+":"+c[id]]={[id]:c[id],[t+"_name"]:c[t+"_name"]}
 });
 return a;
},{})).reduce((a,[k,o],n)=>{
 [n]=k.split(":");
 (a[n]=a[n]||[]).push(o)
 return a;
},{});

console.log(res);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72734178

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档