简体   繁体   English

如何将属性插入嵌套数组的叶节点?

[英]How to insert a property into the leaf nodes of a nested array?

This is my data : https://api.myjson.com/bins/pmzf0 这是我的数据: https : //api.myjson.com/bins/pmzf0

I retrieve all the leaf nodes of that data by using this function : 我使用以下函数检索该数据的所有叶节点:

function getLeafNodes(nodes, result = []) {
    for (var i = 0, length = nodes.length; i < length; i++) {
        if (!nodes[i].children) {
            result.push(nodes[i]);
        } else {
            result = getLeafNodes(nodes[i].children, result);
        }
    }
    return result;
 }

This is the returned result : https://api.myjson.com/bins/12qiq4 这是返回的结果: https : //api.myjson.com/bins/12qiq4

Then I calculated the percentage info of each element by getting its max value then multiplying it by 1.2 to obtain my target Value. 然后,我通过获取每个元素的最大值,然后将其乘以1.2得到我的目标值,从而计算出每个元素的百分比信息。

var maxVal = Math.max.apply(Math, leafs.map(function (o) { return o.value; }))

var targetVal = maxVal * 1.2;

Then I obtain my array of percentages for each element by using the following code : 然后,使用以下代码获取每个元素的百分比数组:

var percentageData = leafs.map(function (o) {
    return { percentage: (o.value / targetVal * 100).toFixed(2) };
})

This returns an array of percentage data : https://api.myjson.com/bins/mnte4 这将返回一个百分比数据数组: https : //api.myjson.com/bins/mnte4

Now how do I insert this back into my original data ? 现在如何将其重新插入原始数据中? Or is my approach wrong and I can straight away calculate the percentage info for each element in my original data without all this steps. 还是我的方法是错误的,我可以立即计算原始数据中每个元素的百分比信息,而无需执行所有这些步骤。

Instead of saving the percentage values in a separate array like, 而不是将百分比值保存在单独的数组中,

var percentageData = leafs.map(function (o) {
    return { percentage: (o.value / targetVal * 100).toFixed(2) };
})

You can add a new percentage field to leafs using foreach like, 您可以使用foreach向叶子添加新的百分比字段,例如

leafs.forEach(function (o) {
   o['percentage'] = (o.value / targetVal * 100).toFixed(2);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM