使用子数组过滤对象



嗨,我正在尝试过滤此对象以获取以下对象结果。某些对象在子数组中可能只有一个子编号。我添加了一个样本和一个所需的结果。

//Curently have 
Object {
"contactType": "person",
"firstName": "Jame Bond",
 "id": "05434909-468F-4AF4-wfde-000000000:ABPerson",
"imageAvailable": false,
 "key": undefined,
"name": "Jame Bond",
 "phoneNumbers": Array [
  Object {
   "countryCode": "us",
    "digits": "+14255556668",
    "id": "53109855-4BA3-4A29-A65C-05B60ED299FA",
    "label": "‎old number",
    "number": "+1 (424) 555-0000",
  },
 Object {
    "countryCode": "gb",
  "digits": "+44712345678",
    "id": "37D77251-39E3-488D-9832-102E7B907E24",
     "label": "mobile",
    "number": "+44712345678",
   },
],
},
//need 
Object {
"name": "James Bond"
  Object {
"digits1": "+14255556668",
"digits2": "+44712345678" // if exists! 
  }
}

有什么建议吗?

像这样?

const { 
  name, 
  phoneNumbers: [ 
    // ':' equals as, and '=' means default value, when prop doesn't exist
    // could be anything you want
    { digits: digits1 }, 
    { digits: digits2 = null } 
  ],
} = yourObject;
const newObject = { name, { digits1, ...digits2 } };

我们只是解构对象并从该变量创建新对象。您可以在此处找到更多信息。

如果电话号码可能非常,我会建议以下代码。

const { name, phoneNumbers } = yourObject;
const allDigits = phoneNumbers.map(({ digits }, i) => ({[`digits${i}`]: digits}));
const newObject = Object.assign({ name }, ...allDigits);

相关内容

  • 没有找到相关文章

最新更新