我有一个对象数组根据其action_type键将数据保存在对象中 我的数组对象数据
var jsonData = [
{
"id":"1000000",
"action_type":"sms"
},{
"id":"1000001",
"action_type":"push"
},{
"id":"1000002",
"action_type":"email"
},{
"id":"1000003",
"action_type":"push"
},{
"id":"1000004",
"action_type":"email"
},{
"id":"1000005",
"action_type":"sms"
}
];
我想根据其action_type将数据存储到多个对象数组中,以便根据其类型执行操作。
var ObjectSms = [{"id":"1000000","action_type":"sms"},{"id":"1000005","action_type":"sms" }];
var ObjectPush = [{"id":"1000001","action_type":"push"},{"id":"1000003","action_type":"push" }];
var ObjectEmail = [{"id":"1000002","action_type":"email"},{"id":"1000004","action_type":"email" }];
,以便根据其操作类型执行操作
if(action_type == "sms"){
sendSmsFunction(ObjectSms);
}
if(action_type == "email"){
sendEmailFunction(ObjectEmail);
}
if(action_type == "push"){
sendPushFunction(ObjectPush);
}
答案 0 :(得分:1)
var jsonData = [
{
"id":"1000000",
"action_type":"sms"
},{
"id":"1000001",
"action_type":"push"
},{
"id":"1000002",
"action_type":"email"
},{
"id":"1000003",
"action_type":"push"
},{
"id":"1000004",
"action_type":"email"
},{
"id":"1000005",
"action_type":"sms"
}
];
let smsArr = [];
let emailArr = [];
let pushArr = [];
jsonData.forEach(obj => {
if (obj.action_type === "sms") {
smsArr.push(obj);
}
if (obj.action_type === "email") {
emailArr.push(obj);
}
if (obj.action_type === "push") {
pushArr.push(obj);
}
});
console.log(smsArr, emailArr, pushArr );
答案 1 :(得分:0)
您可以使用解构分配和 reduce()来获得该结果:
var jsonData = [{
"id": "1000000",
"action_type": "sms"
}, {
"id": "1000001",
"action_type": "push"
}, {
"id": "1000002",
"action_type": "email"
}, {
"id": "1000003",
"action_type": "push"
}, {
"id": "1000004",
"action_type": "email"
}, {
"id": "1000005",
"action_type": "sms"
}];
const {
ObjectSms,
ObjectPush,
ObjectEmail
} = jsonData.reduce((a, c) => {
if (c.action_type === 'sms') {
a.ObjectSms.push(c)
} else if (c.action_type === 'push') {
a.ObjectPush.push(c)
} else if (c.action_type === 'email') {
a.ObjectEmail.push(c)
}
return a
}, {
ObjectSms: [],
ObjectPush: [],
ObjectEmail: []
})
console.log('ObjectSms', ObjectSms)
console.log('ObjectPush', ObjectPush)
console.log('ObjectEmail', ObjectEmail)
解构分配: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Array.prototype.reduce(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
答案 2 :(得分:0)
希望您正在使用lodash。使用lodash过滤器功能,您可以像这样:
var jsonData = [
{
"id":"1000000",
"action_type":"sms"
},{
"id":"1000001",
"action_type":"push"
},{
"id":"1000002",
"action_type":"email"
},{
"id":"1000003",
"action_type":"push"
},{
"id":"1000004",
"action_type":"email"
},{
"id":"1000005",
"action_type":"sms"
}];
const smsArr = [];
const emailArr = [];
_.filter(jsonData, d => {
if(d.action_type == "sms"){
smsArr.push(d)
}
else if (d.action_type == "email"){
emailArr.push(d)
}
})