// 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, но не уверен, как перебирать все дочерние элементы и получать общую стоимость акций отдельной компании
Ребенок-акционеры могут расти в соответствии с потребностями пользователя - кажется, мне нужно реализовать рекурсивную функцию, но я не смог реализовать это тоже. Пожалуйста, помогите... Спасибо
Я добавил MyCorp в ту же структуру (firstName, ownShareholders, percentOwnership, акционеры)
const MyCorp = [{
firstName: 'MyCorp',
ownShareholders: true,
shareholders: [{
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
}
]
}];
const getShareValue = (comp) => comp.reduce((result, current) => result += current.percentageOwnership, 0);
const calc = (comp) => {
let result = {};
comp.forEach((current) => {
if (current.ownShareholders) {
result = Object.assign(result, calc(current.shareholders));
result[current.firstName] = getShareValue(current.shareholders);
}
});
return result;
};
console.log(calc(MyCorp));
Вы можете начать с размещения массива MyCorp
в новом массиве с объектом firstName
и shareholders
такими как остальная часть данных, чтобы вы могли использовать рекурсивный алгоритм.
Тогда это всего лишь вопрос сбора percentageOwnership
каждого акционера и рекурсивного вызова функции в массивах shareholders
.
пример
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
}
];
const data = [
{
firstName: "MyCorp",
shareholders: MyCorp
}
];
const result = data.reduce(function getPercentageOwnership(result, element) {
const { firstName } = element;
if (element.shareholders.length !== 0) {
result[firstName] = 0;
}
element.shareholders.forEach(shareholder => {
result[firstName] += shareholder.percentageOwnership;
getPercentageOwnership(result, shareholder);
});
return result;
}, {});
console.log(result);