对象到数组-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' ] ]