对象转数组 - JavaScript
假设我们有一个键值对的对象,如下所示 −
const obj = { name: "Vikas", age: 45, occupation: "Frontend Developer", address: "Tilak Nagar, New Delhi", experience: 23, salary: "98000" };
我们需要编写一个函数,用于接受对象并返回一个数组的数组,其中每个子数组表示一个键值对
示例
让我们编写此函数的代码 −
const obj = { name: "Vikas", age: 45, occupation: "Frontend Developer", address: "Tilak Nagar, New Delhi", experience: 23, salary: "98000" }; const objectToArray = obj => { const keys = Object.keys(obj); const res = []; for(let i = 0; i < keys.length; i++){ res.push([keys[i], obj[keys[i]]]); }; return res; }; console.log(objectToArray(obj));
输出
控制台中的输出: −
[ [ 'name', 'Vikas' ], [ 'age', 45 ], [ 'occupation', 'Frontend Developer' ], [ 'address', 'Tilak Nagar, New Delhi' ], [ 'experience', 23 ], [ 'salary', '98000' ] ]
广告