假设我们有一个这样的对象-
const dataset = { "diamonds":77, "gold-bars":28, "exciting-stuff":52, "oil":51, "sports-cars":7, "bitcoins":40 };
我们需要编写一个JavaScript函数,该函数接受一个这样的对象,并返回将键及其值分开的对象数组。
因此,对于上述目的,输出应为-
const output = [ {"asset":"diamonds", "quantity":77}, {"asset":"gold-bars", "quantity":28}, {"asset":"exciting-stuff", "quantity":52}, {"asset":"oil", "quantity":51}, {"asset":"bitcoins", "quantity":40} ];
以下是代码-
const dataset = { "diamonds":77, "gold-bars":28, "exciting-stuff":52, "oil":51, "sports-cars":7, "bitcoins":40 }; const splitKeyValue = obj => { const keys = Object.keys(obj); const res = []; for(let i = 0; i < keys.length; i++){ res.push({ 'asset': keys[i], 'quantity': obj[keys[i]] }); }; return res; }; console.log(splitKeyValue(dataset));
输出结果
这将在控制台上产生以下输出-
[ { asset: 'diamonds', quantity: 77 }, { asset: 'gold-bars', quantity: 28 }, { asset: 'exciting-stuff', quantity: 52 }, { asset: 'oil', quantity: 51 }, { asset: 'sports-cars', quantity: 7 }, { asset: 'bitcoins', quantity: 40 } ]