简体   繁体   English

将 3 arrays 转换为 object

[英]Converting 3 arrays into an object

Good day buddy, i'm trying to convert 3 arrays into 1 object. I need each months array length to be in accordance with another arrays length If some one has any idea how to solve it i would be appreciated too much.你好伙计,我正在尝试将 3 arrays 转换为 1 object。我需要每个月的数组长度与另一个 arrays 长度一致如果有人知道如何解决它,我将不胜感激。 Thanks for your time and reading this, have a nice day!感谢您花时间阅读本文,祝您有美好的一天!

Data:数据:

const months = [
    "March 2022",
    "April 2022",
    "May 2022",
    "June 2022"
]

const values = [
    [ "-50" ],
    [ "-100",  "350", "-111" ],
    [ "201", "200" ],
    [ "-290" ]
]

const categories = [
    [ "Credit" ],
    [ "Debt", "Salary", "Credit" ],
    [ "Salary", "Salary" ],
    [ "Investments" ]
]

This is expected result:这是预期的结果:

[
    {
        "name": "March 2022",
        "series": 
            { 
                "name": "Credit" , 
                "value": -50 
            }
        
    },
    {
        "name": "April 2022",
        "series": [
            {
                "name": "Debt",
                "value": -100
            },
            {
                "name": "Salary",
                "value": 350
            },
            {
                "name": "Credit",
                "value": -111
            }
        ]
    },
    {
        "name": "May 2022",
        "series": [
            {
                "name": "Salary",
                "value": 201
            },
            {
                "name": "Salary",
                "value": 200
            }
        ]
    },
    {
        "name": "June 2022",
        "series":
            {
                "name": "Investments",
                "value": -290
            }
        
    }
]

All what i did in last days is this code, but it's not working, before for length of second elements it was working, but, when length of 3rd element increased they start staking together, and this is not all.. I'm using angular's service, and when navigating from 1 route to another their length by index[i] start staking (if manually refresh page by crtl+r it's working).. When firts call in first for loop of console.log(values[i].length) its length are [1, 3, 2, 1] which is correct, but at next call(while going thougth pages) length is [2, 6, 4, 2] and increasing with each call:我最近几天所做的就是这段代码,但它不起作用,在第二个元素的长度之前它是有效的,但是,当第三个元素的长度增加时,它们开始组合在一起,这还不是全部..我正在使用angular 的服务,当从 1 条路线导航到另一条路线时,它们的长度由 index[i] 开始放样(如果通过 crtl+r 手动刷新页面它正在工作)。当第一次调用 console.log(values[i]) 循环时.length) 它的长度是 [1, 3, 2, 1] 这是正确的,但是在下一次调用时(在浏览页面时)长度是 [2, 6, 4, 2] 并且随着每次调用而增加:

 const months = [ "March 2022", "April 2022", "May 2022", "June 2022" ] const values = [ ["-50"], ["-100", "350", "-111"], ["201", "200"], ["-290"] ] const categories = [ ["Credit"], ["Debt", "Salary", "Credit"], ["Salary", "Salary"], ["Investments"] ] let result = []; let subArray1 = []; let subArray2 = []; for (let i = 0; i < values.length; i++) { // if 1 expense per month push to subArray1 => result if (values[i].length == 1) { subArray1.push([{ "name": categories[i], "value": +values[i] }]) } else { for (let j = 0; j < values[i].length; j++) { // if more then 1 expense per month push to subArray2 => subArray1 => result subArray2.push({ "name": categories[i][j], "value": +values[i][j] }); }; subArray1.push(subArray2); }; }; //combine all together for (let i = 0; i < months.length; i++) { result.push({ "name": months[i], "series": subArray1[i] }); };

You can generate the results you want with a nested map , first on the month name and then the categories , using the second ( index ) parameter to the callback to select the appropriate values from the other arrays:您可以使用嵌套的map生成您想要的结果,首先是month名称,然后是categories ,使用第二个( index )参数回调到 select 来自其他 arrays 的适当值:

 const months = [ "March 2022", "April 2022", "May 2022", "June 2022" ] const values = [ ["-50"], ["-100", "350", "-111"], ["201", "200"], ["-290"] ] const categories = [ ["Credit"], ["Debt", "Salary", "Credit"], ["Salary", "Salary"], ["Investments"] ] const result = months.map((m, mnum) => ({ name: m, series: categories[mnum].map((c, cnum) => ({ name: c, value: +values[mnum][cnum] })) })) console.log(result)

Note that this code always returns an array for series , it seems that would be easier to process than trying to figure out if was an array or an object.请注意,这段代码总是为series返回一个数组,这似乎比试图弄清楚是数组还是 object 更容易处理。

To achieve your result, I have created a function which constructs the series array and a main function which uses the series function into it.为了达到你的结果,我创建了一个 function 来构造series数组,并创建了一个主要的 function,它使用series function 到它里面。

 let months = [ "March 2022", "April 2022", "May 2022", "June 2022" ] let values = [ ["-50"], ["-100", "350", "-111"], ["201", "200"], ["-290"] ] const categories = [ ["Credit"], ["Debt", "Salary", "Credit"], ["Salary", "Salary"], ["Investments"] ] const mapSeries = (index) => (values[index] || []).map((value, vindex) => ({ name: categories[index][vindex], value })) const output = months.map((name, index) => ({ name, series: mapSeries(index) })) console.log(output)

Note: If each element array length of values and categories are not same, then in the mapSeries function, we can do something like categories[index]?.[vindex] || 'not assigned')注意:如果valuescategories的每个元素数组长度不相同,那么在mapSeries function中,我们可以做类似categories[index]?.[vindex] || 'not assigned') categories[index]?.[vindex] || 'not assigned') to avoid errors. categories[index]?.[vindex] || 'not assigned')以避免错误。

You're almost there you just need a small change in your code and you'll be good.你几乎已经完成了,你只需要对你的代码做一点小改动就可以了。

  1. You need to initialise subArray2 inside loop on each iteration as we need separate array every time.您需要在每次迭代时在循环内初始化 subArray2,因为我们每次都需要单独的数组。
  2. You can drop off if condition as the inner for loop will anyway takes care of it irrespective of number of values您可以放弃 if 条件,因为无论值的数量如何,内部 for 循环都会处理它

 let months = ["March 2022","April 2022","May 2022","June 2022"] let values = [["-50"],["-100", "350", "-111"],["201", "200"],["-290"]] const categories = [["Credit"],["Debt", "Salary", "Credit"],["Salary", "Salary"],["Investments"]] let result = []; let subArray1 = []; for (let i = 0; i < values.length; i++) { let subArray2 = []; for (let j = 0; j < values[i].length; j++) { subArray2.push({ "name": categories[i][j], "value": +values[i][j] }); }; subArray1.push(subArray2) }; //combine all together for (let i = 0; i < months.length; i++) { result.push({ "name": months[i], "series": subArray1[i] }); }; console.log(result)

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

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