将键和值拆分为独立对象——JavaScript
假设,我们有这样一个对象 −
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 } ]
广告