简体   繁体   中英

Manipulate object to make different format

sorry for the stupid question but I am also looking for a nice solution for this problem:

I have this object

var obj = {
    "brand[]" : [1,2,3],
    "model[]" : [1,2,3],
    "varqnt[]" : [1,2,3]
}

Now what I want is to make a new object/array ( i don't think it matters for now ) from it which should be

var newObj = {
    'row-1': {
        brand[] : 1,
        model[] : 1,
        varqnt[] : 1
    },
    'row-2': {
        brand[] : 2,
        model[] : 2,
        varqnt[] : 2
    },
    'row-3': {
        brand[] : 3,
        model[] : 3,
        varqnt[] : 3
    }
}

The tricky part is that 'brand[]', 'model[]', 'varqnt[]' might not all be there.

I will try to explain a bit more... basically the first object is comming from url params, of 2 select boxes and 1 input, but since I use the same form in different "places" this varqnt[] ( the input ) might not be presented.

I am not sure if anyone will understand me.. but english is not mother's language as an excuse :P

Thanks, and if I wrote something totaly unclear sorry :(

You can achieve this with two loops. For example:

 var obj = { "brand[]": [12, 2, 3], "model[]": [1, 2, 32], "varqnt[]": [1, 21, 3] }; var newObj = {}; Object.keys(obj).forEach(function(key) { obj[key].forEach(function(el, i) { if (typeof newObj['row-' + i] == "undefined") { newObj['row-' + i] = {}; } newObj['row-' + i][key] = el; }); }); alert(JSON.stringify(newObj, null, 4)); 

Well you can do something like this and access each element in your object

var newObj = {};
for (data in obj){
console.log(obj[data])
}

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