【发布时间】:2018-07-31 10:49:39
【问题描述】:
// Hi, I am having following array of data
const MyCorp = [{
firstName: "ABC Corp",
ownShareholders: true,
percentageOwnership: 50,
shareholders: [{
firstName: "XYZ Corp",
percentageOwnership: 50,
ownShareholders: false,
shareholders: []
},
{
firstName: "DEF Corp",
ownShareholders: true,
percentageOwnership: 60,
shareholders: [{
firstName: "SAY Corp",
percentageOwnership: 50,
ownShareholders: false,
shareholders: []
},
{
firstName: "No Corp",
ownShareholders: false,
percentageOwnership: 50,
shareholders: []
}
]
}
]
},
{
firstName: "Test Corp",
ownShareholders: false,
shareholders: [],
percentageOwnership: 50
}
]
// A trying to iterate over the data to get below output
// MyCorp share value = 50+ 50 == 100 (50 is from ABC Corp and 50 is of Test Corp)
// ABC Corp share value = 50 + 60 ===110(50 is from XYZ Corp and 60 is of DEF Corp)
// DEF Corp Share value = 50+ 50 === 100(50 is from SAY Corp and 50 is of No Corp)
// Output can be a object or array
// What I did to achieve this
const ShareArray = (shareholders) => {
const something = [];
shareholders.forEach((shareholder) => {
if (shareholder.ownShareholders === true) {
something.push(shareholder.shareholders);
}
});
return validateSharePercentage(something[0])
};
const validateSharePercentage = shareholders => {
let value = 0;
shareholders.forEach(shareholder => {
value += shareholder.percentageOwnership;
});
return value;
};
const somevalue = validateSharePercentage(MyCorp);
console.log(somevalue);
const arrayValues = ShareArray(MyCorp);
console.log(arrayValues);
我得到 100 和 110,但不知道如何遍历所有子项并获得单个公司的总股票价值
子股东可能会根据用户需求增长 - 似乎我需要实现递归函数,但我也未能实现 请帮忙... 谢谢
【问题讨论】:
标签: javascript