将 JavaScript 对象转换为值数组 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming
我们需要从 JavaScript 对象创建一个数组,其中包含该对象所有属性的值。例如,给定此对象 −
{ "firstName": "John", "lastName": "Smith", "isAlive": "true", "age": "25" }
我们必须生成这个数组 −
const myarray = ['John', 'Smith', 'true', '25'];
示例
以下是代码 −
Solution1
const obj = { "firstName": "John", "lastName": "Smith", "isAlive": "true", "age": "25" }; const objectToArray = obj => { const keys = Object.keys(obj); const res = []; for(let i = 0; i < keys.length; i++){ res.push(obj[keys[i]]); }; return res; }; console.log(objectToArray(obj));
输出
这将在控制台中产生以下输出 −
[ 'John', 'Smith', 'true', '25' ]
Solution 2 − One line alternate −
const obj = { "firstName": "John", "lastName": "Smith", "isAlive": "true", "age": "25" }; const res = Object.values(obj); console.log(res);
输出
这将在控制台中产生以下输出 −
[ 'John', 'Smith', 'true', '25' ]