2017-08-24 48 views
-3

變換數組對象的數組。例如,如何改造:如何通過Lodash

[ 
    "20170101|9,4,4,2,6", 
    "20170102|0,7,5,6,2" 
] 

[ 
    { 
    date:"20170101" 
    numbers:[9, 4, 4, 2, 6] 
    sum:25 
    oddOrEven:'odd', 
    }, 
    { 
    date:"20170102", 
    numbers:[0, 7, 5, 6, 2], 
    sum:20, 
    oddOrEven:'even', 
    } 
] 

這是好得多,如果沒有中間變量使用lodash。

+0

https://lodash.com/docs/#map'_.map(myarray的,parseItem);'你可以編寫你自己的函數來解析一行到一個對象。 – JamesT

回答

1

沒有一條線,但它會給你一個想法如何做到這一點。

var a =[ 
 
    "20170101|9,4,4,2,6", 
 
    "20170102|0,7,5,6,2" 
 
]; 
 

 

 
a = _.map(a, function(o){ 
 
    
 
    var split = o.split('|'), 
 
     numbers = _.map(split[1].split(','), _.ary(parseInt, 1)), 
 
     sum  = _.sum(numbers); 
 

 
    return { 
 
     date: split[0], 
 
     numbers: numbers, 
 
     sum: sum, 
 
     oddOrEven: (sum % 2 == 0 ? 'even' : 'odd') 
 
    } 
 

 
}); 
 

 
console.log(a);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

0

你可以做這樣的事情:

var aryData = [ "20170101|9,4,4,2,6", "20170102|0,7,5,6,2"] 
 
    ,aryObjects = []; 
 
for(var i in aryData) { 
 
    var aryFields = aryData[i].split("|"); 
 

 
    if (aryFields.length != 2) { 
 
     continue; 
 
    } 
 
    var aryNumbers = aryFields[1].split(","), intSum = 0; 
 

 
    for(var n in aryNumbers) { 
 
     aryNumbers[n] = parseInt(aryNumbers[n]); 
 
     intSum += aryNumbers[n]; 
 
    } 
 
    aryObjects.push({date:aryFields[0] 
 
       ,numbers:aryNumbers 
 
        ,sum:intSum 
 
       ,oddorEven:(((intSum % 2) == 0) ? "even" : "odd")}); 
 
} 
 
console.dir(aryObjects);