简体   繁体   中英

Create JSON based another JSON as key and value?

I have json like

SampJson= [
    {
        data: "50",
        cIndex: "column0",rowno:"1"
    },
    {
        data: "5",
        cIndex: "column1",rowno:"1"
    },
    {
        data: "80",
        cIndex: "column0",rowno:"2"
    },
    {
        data: "65",
        cIndex: "column1",rowno:"2"
    }

];

I need to create a JSON like

[
    {
        rowno:1,
        column0:50,
        column1:5
    },
    {
        rowno:2,
        column0:80,
        column1:65
    }
];

Thanks in advance...

You should just do this:

 sampJson = [ { data: "50", cIndex: "column0", rowno: "1" }, { data: "5", cIndex: "column1", rowno: "1" }, { data: "80", cIndex: "column0", rowno: "2" }, { data: "65", cIndex: "column1", rowno: "2" } ]; var results = []; sampJson.forEach(function(el) { if (results[+el.rowno - 1] == null) { results[+el.rowno - 1] = new Object(); } results[+el.rowno - 1].rowno = +el.rowno; results[+el.rowno - 1][el.cIndex] = +el.data; }); console.log(results); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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