将键和值拆分为单独的对象 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming
假设,我们有一个像这样的对象 −
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 } ]