javascript - How to build out this complex Array based on this Simple Object -
http://jsfiddle.net/leongaban/tuhgns3q/
my simple object:
{ portfolio: "aapl", t1_tag1: "1111", t2_tag1: "2222", t3_tag1: "3333", ticker1: "aa", ticker2: "goog", ticker3: "aapl" }
the desired end result below. array objects containing array of objects:
[ 0:object { tags: [ 0:object { t1_tag1: "1111" } ] ticker: ticker1 }, 1:object { tags: [ 0:object { t2_tag2: "2222" } ] ticker: ticker2 }, 3:object { tags: [ 0:object { t3_tag3: "3333" } ] ticker: ticker3 } ]
is there simplier way accomplish _lodash?
here's came using vanilla javascript , no lodash or underscore:
function expand(simple) { var outerarray = [], innerarray, outerindex = 1, innerindex, outerobject, innerobject; while (("ticker" + outerindex) in simple) { innerarray = []; innerindex = 1; while (("t" + outerindex + "_tag" + innerindex) in simple) { innerobject = {}; innerobject["t" + outerindex + "_tag" + innerindex] = simple["t" + outerindex + "_tag" + innerindex]; innerarray.push(innerobject); innerindex++; } outerobject = { tags: innerarray, ticker: simple["ticker" + outerindex] }; outerarray.push(outerobject); outerindex++; } return outerarray; } console.log(expand({ portfolio: "aapl", t1_tag1: "1111", t2_tag1: "2222", t3_tag1: "3333", ticker1: "aa", ticker2: "goog", ticker3: "aapl" }));
Comments
Post a Comment