如何解决如何将`control`数组中其余项的`currencyId`和`currencyCode`分叉
我想将currencyId
数组中其余项目的currencyCode
和control
分叉。
现在它给出的输出是:
[{
channels: {ANDROID: 0,EMAIL: 0,INBox: 0,IOS: 0,SMS: 0,TELEGRAM: 0,currencyCode: "CFA",currencyId: 11},currency: {currencyCode: "CFA",currencyId: 11}
}]
但是我想要输出:
[{
channels: {ANDROID: 0,TELEGRAM: 0},currencyId: 11}
}]
到目前为止,这是我的代码:
let chargesData = [
{
"SMS": 0,"IOS": 0,"ANDROID": 0,"EMAIL": 0,"currencyId": 11,"currencyCode": "CFA","TELEGRAM": 0,"INBox": 0
},{
"SMS": 10,"IOS": 10,"ANDROID": 10,"EMAIL": 10,"currencyId": 12,"currencyCode": "IND","TELEGRAM": 10,"INBox": 10
}
]
let control = [];
let currency;
for(let charges of chargesData) {
let chargesChannels = Object.keys(charges)
let currencyCode = chargesChannels.indexOf("currencyCode");
let currencyId = chargesChannels.indexOf("currencyId");
chargesChannels.splice(currencyCode,1);
chargesChannels.splice(currencyId,1);
currency = { currencyCode: charges.currencyCode,currencyId: charges.currencyId };
control.push({
channels: charges,currency: currency
})
}
console.log(control);
该怎么做?
解决方法
您可以使用.map
和destructuring
进行此操作:
let chargesData = [
{
"SMS": 0,"IOS": 0,"ANDROID": 0,"EMAIL": 0,"currencyId": 11,"currencyCode": "CFA","TELEGRAM": 0,"INBOX": 0
},{
"SMS": 10,"IOS": 10,"ANDROID": 10,"EMAIL": 10,"currencyId": 12,"currencyCode": "IND","TELEGRAM": 10,"INBOX": 10
}
]
const arr = chargesData.map(e => {
const {currencyCode,currencyId,...channels} = e;
return {
channels: channels,currency: {currencyCode,currencyId}
}
});
console.log(arr);
,
您可以使用in
运算符遍历数组,然后遍历对象属性,然后根据需要分离出对象。
let chargesData = [
{
"SMS": 0,"INBOX": 0
},"INBOX": 10
}
];
const controls = [];
chargesData.forEach(charges=>{
const control={
channels:{},currency:{}
}
for (const key in charges) {
if(["currencyCode","currencyId"].includes(key)){
control.currency[key]=charges[key];
}else{
control.channels[key]=charges[key];
}
}
controls.push(control);
});
console.log(controls);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。