我正在尝试过滤一个数组并使用 lodash 从地址簿中获取电话号码,结构类似于
var obj = {
'contacts': [{
'id': 1,
'displayName': 'John Doe',
'phonenumbers': [{
'id': '1',
'type': 'mobile',
"pref":false,
'value': '555-555'
}, {
'id': '2',
'type': 'mobile',
"pref":false,
'value': '555-554'
}]
}, {
'id': 2,
'displayName': 'Jane Doe',
'phonenumbers': [{
'id': '1',
'type': 'mobile',
"pref":false,
'value': '555-557'
}]
}]
}
我可以尝试通过以下方式联系电话号码:
lodash.map(
contacts,
function(person) {
return { id: person.id,
displayName: person.displayName,
phoneNumbers: [
{
number: person.phoneNumbers[0].value,
type: person.phoneNumbers[0].type}
],
photos: person.photos };
}
);
但是当我想用 person.phoneNumbers[1].value 得到 2 和 third 时,当没有第二个电话号码时我会出错,有没有办法在不指定数组位置的情况下得到它们? 输出应该是一个包含联系人 ID 以及电话号码和类型的新数组。
var ouptput= {
'contacts': [{
'id': 1,
'phonenumbers': [{
'type': 'mobile',
'value': '555-555'
}, {
'type': 'mobile',
'value': '555-554'
}]
}, {
'id': 2,
'phonenumbers': [{
'type': 'mobile',
'value': '555-557'
}]
}]
}
最佳答案
如果您使用的是 es6,则不再需要 lodash。
contacts.map( ({ id, phonenumbers }) =>
({ id, phonenumbers: phonenumbers.map( ({ value, type }) => ({ value, type }) ) })
);
你得到了你想要的精确输出。
关于javascript - lodash 在深层嵌套数组和对象上使用 map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39569482/