我正在使用json:
[ { status: 'complete',
type: 'bid',
amount: 0,
units: 0,
activeId: 146,
id: 3 },
{ status: 'complete',
type: 'ask',
amount: 0,
units: 0,
activeId: 146,
id: 1 },
{ status: 'pending',
type: 'ask',
amount: '1009',
units: 0.996,
activeId: 146,
id: 2,
env: 'newInsert' },
{ status: 'complete',
type: 'ask',
amount: 0,
units: 0,
id: 2,
activeId: 146 },
{ status: 'complete',
type: 'bid',
amount: 0,
units: 0,
activeId: 146,
id: 4 },
{ status: 'pending',
type: 'bid',
amount: 1012,
units: 3.004,
id: 11,
activeId: 146,
env: 'newInsert' } ]
在这个数组中,我需要删除id相同的对象,并从状态" pending"到"完成" 例如:
{ status: 'pending',
type: 'ask',
amount: '1009',
units: 0.996,
activeId: 146,
id: 2,
env: 'newInsert' },
{ status: 'complete',
type: 'ask',
amount: 0,
units: 0,
id: 2,
activeId: 146 }
here same id of type ask and status changed pending to complete.
我试图以一般的方式循环使用foreach并匹配并提取结果但是有任何特定的方法或任何过滤器将事物分组并提取。
答案 0 :(得分:0)
使用函数func setTextViewSizeWithContent() {
let newSize = self.calculateSize(chatTextView: self.messageTF, chatText: self.messageTF.text, withFixedSize: kMessageViewWidths)
self.messageTF.frame = CGRect(x: yourXPosition, y: newYposition,
width: yourTextViewWidth, height: newsize.height)
self.view.layoutIfNeeded()
}
和filter
some
var array = [{ status: 'complete', type: 'bid', amount: 0, units: 0, activeId: 146, id: 3 }, { status: 'complete', type: 'ask', amount: 0, units: 0, activeId: 146, id: 1 }, { status: 'pending', type: 'ask', amount: '1009', units: 0.996, activeId: 146, id: 2, env: 'newInsert' }, { status: 'complete', type: 'ask', amount: 0, units: 0, id: 2, activeId: 146 }, { status: 'complete', type: 'bid', amount: 0, units: 0, activeId: 146, id: 4 }, { status: 'pending', type: 'bid', amount: 1012, units: 3.004, id: 11, activeId: 146, env: 'newInsert' }];
var result = array.filter(o => {
var transition = o.status === 'pending' ? 'complete' : 'pending';
return !(array.some((io) => io.id == o.id && io.status === transition));
});
console.log(result);
答案 1 :(得分:0)
要删除具有相同ID的项目,可以按id创建对象,然后检查长度(使用reduce):
var arr = [{ status: 'complete', type: 'bid', amount: 0, units: 0, activeId: 146, id: 3 }, { status: 'complete', type: 'ask', amount: 0, units: 0, activeId: 146, id: 1 }, { status: 'pending', type: 'ask', amount: '1009', units: 0.996, activeId: 146, id: 2, env: 'newInsert' }, { status: 'complete', type: 'ask', amount: 0, units: 0, id: 2, activeId: 146 }, { status: 'complete', type: 'bid', amount: 0, units: 0, activeId: 146, id: 4 }, { status: 'pending', type: 'bid', amount: 1012, units: 3.004, id: 11, activeId: 146, env: 'newInsert' }];
var map = arr.reduce((ac, x) => ({
...ac,
[x.id]: [...(ac[x.id] || []), x]
}), {})
var res = Object.keys(map).reduce((ac, x) =>
map[x].length > 1 &&
map[x].some(z => z.status == 'pending') &&
map[x].some(z => z.status == 'complete') ?
ac : [...ac, ...map[x]], [])
console.log(res)