嘿,我想使用lodash从对象数组中计算一个属性的总和
假设对象数组看起来像这样...
#find all your connected components (white blobs in your image)
nb_components, dotput, stats, centroids = cv2.connectedComponentsWithStats(thresh, connectivity=8)
#connectedComponentswithStats yields every seperated component with information on each of them, such as size
#the following part is just taking out the background which is also considered a component, but most of the time we don't want that.
sizes = stats[1:, -1]; nb_components = nb_components - 1
# minimum size of particles we want to keep (number of pixels)
#here, it's a fixed value, but you can set it as you want, eg the mean of the sizes or whatever
min_size = 50
#your answer image
img2 = numpy.zeros((dotput.shape))
#for every component in the image, you keep it only if it's above min_size
#thresh[output == 5 + 1] = 0
dots = []
for i in range(0, nb_components):
if sizes[i] < min_size:
dots.append(centroids[i])
#print(dots)
if dots:
dots.sort(key = lambda x: abs(x[1]-digitCenY))
print(dots)
pDot = -1
for i in range(len(digitCenX)):
if (dots[0][0] <= digitCenX[i]) and (i > 0):
pDot = 0
break
elif (digitCenX[i] <= dots[0][0]) and (i != len(digitCenX)-1):
pDot = 0
break
else:
pDot = 1
cv2.rectangle(output, (int(dots[pDot][0]), int(dots[pDot][1])), (int(dots[pDot][0]) + 3, int(dots[pDot][1]) + 3), (0, 255, 0), 1)
我想使用lodash计算该对象的'牛奶'总和。
答案 0 :(得分:0)
类似这样的东西
const bills = salary.map((s)=> s.bills)
_(bills).map((objs,key)=>({
'milk': _.sumBy(objs, 'milk')
})).value
答案 1 :(得分:0)
使用嵌套的_.sumBy()
调用。内部人员从一个milk
中获得salary
的总和,外部人员将所有薪金相加:
const data = {"salary":[{"bills":[{"electricity":300,"milk":500},{"electricity":240,"milk":200},{"electricity":800,"milk":900}]}]}
const result = _.sumBy(data.salary, ({ bills }) => _.sumBy(bills, 'milk'))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>