功能:
var fruitArry=[{name:'durian'},{name:'peach'},{name:'banana'},{name:'pitaya'},{name:'apple'},{name:'cherry'}];
var fruit={'banana':'香蕉','peach':'桃子','durian':'榴莲','pitaya':'火龙果'};
将 fruitArry 中 name 的值根据 fruit 的 key 值进行替换:如果 fruitArry 的值在 fruit 中也有,那就将 fruitArry 替换为 fruit 的值,如果没有,则值不变。
方法一:
<script type="text/javascript"> var fruitArry = [{ name: 'durian' }, { name: 'peach' }, { name: 'banana' }, { name: 'pitaya' }]; var fruit = { 'banana': '香蕉', 'peach': '桃子', 'durian': '榴莲', 'pitaya': '火龙果' }; for (var key in fruit) { for (var i = 0; i < fruitArry.length; i++) { if (key == fruitArry[i].name) { fruitArry[i].name = fruit[key]; } } } console.log(fruitArry); </script>
方法二:
1 <script type="text/javascript"> 2 var fruitArry = [{ 3 name: 'durian' 4 }, { 5 name: 'peach' 6 }, { 7 name: 'banana' 8 }, { 9 name: 'pitaya' 10 }, { 11 name: 'apple ' 12 }, { 13 name: 'cherry ' 14 }]; 15 var fruit = { 16 'banana': '香蕉', 17 'peach': '桃子', 18 'durian': '榴莲', 19 'pitaya': '火龙果' 20 }; 21 fruitArry.forEach(function(item) { 22 if (fruit[item.name]) { 23 item.name = fruit[item.name]; 24 } 25 }); 26 console.log(fruitArry); 27 </script>
方法三:
<script type="text/javascript"> var fruitArry = [{ name: 'durian' }, { name: 'peach' }, { name: 'banana' }, { name: 'pitaya' }, { name: 'apple ' }, { name: 'cherry ' }]; var fruit = { 'banana': '香蕉', 'peach': '桃子', 'durian': '榴莲', 'pitaya': '火龙果' }; fruitArry = fruitArry.map(function(item) { if (fruit[item.name]) { return { name: fruit[item.name] } } else { return { name: item.name } } }); console.log(fruitArry); </script>
打印结果: