2017-06-27 26 views
0

我有一个包含一个数据排序制度若干对象: 价格:产生不同对象的对象数组的Javascript

'btc-usd' : 2640, 'ltc-usd': 40, ... 

加密的金额:

'btc-usd': 2.533, 'ltc-usd': 10.42, ... 

我怎样才能把这些对象和创建一组物体如:

[ { name: 'Bitcoin', amount: 2.533, value: 2640, id: 'btc-usd' }, 
{ name: 'Litecoin', amount: 10.42, value: 40, id: 'ltc-usd' }, ... 
] 

非常感谢您的帮助!

回答

0

您可以映射对象之一的键产生对象的一个​​新的数组。你只需要确定,关键在于每一个这些对象。

const names = { 
    'btc-usd' : 'Bitcoin', 
    'ltc-usd': 'Litecoin', 
    ... 
} 

const prices = { 
    'btc-usd' : 2640, 
    'ltc-usd': 40, 
    ... 
} 

const amounts = { 
    'btc-usd': 2.533, 
    'ltc-usd': 10.42, 
    ... 
} 

const cryptos = Object.keys(names).map((key, index) => ({ 
    name: names[key], 
    amount: amounts[key] , 
    value: prices[key]}, 
    id: key 
})); 
+0

非常感谢!工作完美! –

0

您可以使用哈希映射(例如'btc-usd'=> {name:“Bitcoin”,...})来创建新对象。这个hashmap可以很容易地转换为一个数组。

var input={ 
    value:{'btc-usd' : 2640, 'ltc-usd': 40}, 
    amount:{'btc-usd': 2.533, 'ltc-usd': 10.42}, 
    name:{"btc-usd":"Bitcoin","ltc-usd":"Litecoin"} 
}; 

var hash={}; 
for(key in input){ 
    var values=input[key]; 
    for(id in values){ 
     if(!hash[id]) hash[id]={id:id}; 
     hash[id][key]=values[id]; 
    } 
} 

var output=Object.values(hash); 

http://jsbin.com/fadapafaca/edit?console

+0

非常感谢您的回答! –

0

这里的一个广义功能,add,接受一个字段名称和值的目的,并将它们映射到其然后可以被映射到一个数组一个result对象。

const amounts = {btc: 123.45, eth: 123.45}; 
 
const names = {btc: 'Bitcoin', eth: 'Etherium'}; 
 

 
const result = {}; 
 

 
const add = (field, values) => { 
 
    Object.keys(values).forEach(key => { 
 
    // lazy initialize each object in the resultset 
 
    if (!result[key]) { 
 
     result[key] = {id: key}; 
 
    } 
 

 
    // insert the data into the field for the key 
 
    result[key][field] = values[key]; 
 
    }); 
 
} 
 

 
add('amount', amounts); 
 
add('name', names); 
 

 
// converts the object of results to an array and logs it 
 
console.log(Object.keys(result).map(key => result[key]));

+0

感谢您帮助瑞恩! –

0
const prices = { 
    'btc-usd' : 2640, 
    'ltc-usd': 40 
}; 

const amounts = { 
    'btc-usd': 2.533, 
    'ltc-usd': 10.42 
}; 

首先,创建了每个缩写代表的字典。

const dictionary = { 
    'btc': 'Bitcoin', 
    'ltc': 'Litecoin' 
}; 

然后,用包含相关信息的对象填充一个空数组。在这些对象中的每一个中,名称都将对应于dictionary对象内的相关键。同时,金额和金额将分别对应amountsprices对象中的相关金钥。最后,Id将对应于key本身。

const money = []; 

for(let coin in prices) { 
    money.push({ 
    name: dictionary[coin.substr(0, coin.indexOf('-'))], 
    amount: amounts[coin], 
    value: prices[coin], 
    id: coin 
    }); 
} 

console.log(money);