展平具有数组的对象数组

时间:2020-07-10 15:06:45

标签: javascript arrays

使用javascript Array方法,我希望将其展平:

accounts: [
                {
                                id: 129,
                                contacts: [932, 552, 803]
                },
                {
                                id: 433,
                                contacts: [932, 606]
                }
]

对此:

[932,552,803,606]

注意唯一的联系人。有解决方案吗?

4 个答案:

答案 0 :(得分:1)

我认为这是您要寻找的,您只需要循环数组并使用array.push方法将其推入res数组(如果不存在)

var accounts = [
                {
                     id: 129,
                     contacts: [932, 552, 803]
                },
                {
                     id: 433,
                     contacts: [932, 606]
                }
             ]

var res =[];
accounts.forEach(obj => obj.contacts.forEach(ob=> {

if(!res.includes(ob)){res.push(ob)}
}))

console.log(res);

答案 1 :(得分:1)

进行一些映射,然后调用es6功能Set

let accounts =[
  {
    id: 129,
    contacts: [932, 552, 803]
  },
  {
    id: 433,
    contacts: [932, 606]
  }
]

var contacts = [];

accounts.map(function(item){
    return item.contacts.map(function(contact){
    contacts.push(contact)
  })
})

contactsWithNoDups = Array.from(new Set(contacts));

console.log(contactsWithNoDups);

答案 2 :(得分:0)

或者,有两种方法可以做到这一点:

const accounts= [{id: 129, contacts: [932, 552, 803]},
                 {id: 433, contacts: [932, 606]}],
 r1=Object.keys(accounts.reduce((a,{contacts})=>(contacts.forEach(c=>a[c]=1),a),{})).sort(),
 r2=[... new Set(accounts.reduce((a,{contacts})=>a.concat(contacts),[]))];

console.log('r1:',r1);  
console.log('r2:',r2);

答案 3 :(得分:0)

我会选择一种简单易读的格式:

<p id="we">Default text</p>
<input id="in">
<button onclick="modo()" id="sub">Submit</button>

但是,是的,已经有很多关于此事的文档和主题了……在发布之前,您可能已经做了一些研究

相关问题