2016-07-22 65 views

回答

2

如果更改爲有效的JS數據,您可以用reduce()

var obj = { 
 
    dis: ["String1", "String2", "String3"], 
 
    par: "pony" 
 
} 
 

 
var result = obj.dis.reduce(function(r, e) { 
 
    r.push({name: e, value: obj.par}); 
 
    return r; 
 
}, []); 
 

 
console.log(result)
做到這一點

0

你可以很容易地做到這一點,但要注意你有雙括號(鬍鬚和方括號)。

var 
    data = { 
     dis: ["String1","String2","String3"], 
     par: "pony" 
    }, 

    result = []; 

for (var index in data.dis) 
    result.push({ name: data.dis[index], value: data.par} 

你可以找到小提琴here

0

可以使用Array.protoype.map做到這一點:

var obj = { 
 
    dis:["String1","String2","String3"], 
 
    par:"pony" 
 
}; 
 

 
var arrOfObj = obj.dis.map(function(name) { 
 
    return { 
 
     name: name, 
 
     value: obj.par 
 
    } 
 
}); 
 

 
console.log(arrOfObj)

或者lodash的_.map

var obj = { 
 
    dis:["String1","String2","String3"], 
 
    par:"pony" 
 
}; 
 

 
var arrOfObj = _.map(obj.dis, function(name) { 
 
    return { 
 
     name: name, 
 
     value: obj.par 
 
    } 
 
}); 
 

 
console.log(arrOfObj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

相關問題