我正在尝试在一个对象数组上处理这个规则 如果有一个或多个类型等于固定电话的对象返回第一个数字,如果没有带有type = landline的对象,则返回第一个数字只有当它的type属性不同于mobile时,如果它等于mobile返回下一个数字如果可用,否则返回空白值
var phoneObject = [
{
type: 'mobile',
phone: '0123456789'
},
{
type: 'mobile',
number:'78945610'
}
{
type:'landline'
number:'15975345'
}
];
var number = phoneObject.reduce((a,b)=>{
if (a.type === 'landline' && b.type === 'landline') {
b.number = a.number;
}
else {
if (a.type !== 'landline' && b.type !== 'landline') {
if (a.type !== 'mobile') {
b.number = a.number;
} else {
if (b.number) {
return b.number;
}
else {
b.number = '';
}
}
}
}
return b.number;
});
console.log(number);
// should return the third number for this array
var phoneObject = [
{
type: 'mobile',
phone: '0123456789'
},
{
type: 'mobile',
number:'78945610'
}
{
type:'landline'
number:'15975345'
}
];
// for this one it should return the first
var phoneObject = [
{
type: 'landline',
phone: '0123456789'
},
{
type: 'mobile',
number:'78945610'
}
{
type:'landline'
number:'15975345'
}
];
// for this one it should return the second number
{
type: 'mobile',
phone: '0123456789'
},
{
type: 'mobile',
number:'78945610'
}
];
// and for this last one it should return a blank value
var phoneObject = [
{
type: 'mobile',
phone: '0123456789'
},
];
感谢您的帮助 最好的祝福, 萨拉
答案 0 :(得分:0)
这个评论太长了,但是......
你忘了两个逗号:
{
type: 'mobile',
number:'78945610'
}
{
type:'landline'
number:'15975345'
}
必须编辑为:
{
type: 'mobile',
number:'78945610'
},
{
type:'landline',
number:'15975345'
}
答案 1 :(得分:0)
你可以做一些体面的检查并保存第二个号码。仅在没有固定电话号码的情况下使用它。
此提案适用于Array#reduce
。
library(dplyr)
df <- mtcars %>% group_by(cyl, mpg)
groups(df)
[[1]]
cyl
[[2]]
mpg
&#13;
与上述相同,但Array#some
function getNumber(array) {
var counter = 0,
second = '';
return array.reduce(function (r, o) {
if (r) {
return r;
}
if (o.type === 'landline') {
return o.number;
}
counter++;
if (counter === 2) {
second = o.number;
}
}, '') || second;
}
//should return the third number for this array
var phoneObject1 = [{ type: 'mobile', number: '0123456789' }, { type: 'mobile', number:'78945610' }, { type: 'landline', number:'15975345' }];
// for this one it should return the first
var phoneObject2 = [{ type: 'landline', number: '0123456789' }, { type: 'mobile', number:'78945610' }, { type:'landline', number:'15975345' }];
// for this one it should return the second number
var phoneObject3 = [{ type: 'mobile', number: '0123456789' }, { type: 'mobile', number:'78945610' }];
//and for this last one it should return a blank value
var phoneObject4 = [{ type: 'mobile', number: '0123456789' }];
console.log([phoneObject1, phoneObject2, phoneObject3, phoneObject4].map(getNumber));
&#13;