如何将传入的对象转换为字符串数组

时间:2016-07-25 21:19:32

标签: javascript arrays for-in-loop

function objectToArray (object) {
   var array = [];
   var str = "";
   for (var key in object) {
       array.push(key);
       array.push(object[key]);
       if (object.hasOwnProperty(key)) {
             str += key + " is "  + object[key] + "";
       }
     }
   console.log(array);
 }
 objectToArray({name: "Marcia", age: 101});

输出为[ 'name', 'Marcia', 'age', 101 ],我需要它为["name is Marcia", "age is 101"]

2 个答案:

答案 0 :(得分:3)

而不是:

   array.push(key);
   array.push(object[key]);
   if (object.hasOwnProperty(key)) {
         str += key + " is "  + object[key] + "";
   }

你想要这个:

   if (object.hasOwnProperty(key)) {
         array.push( key + " is "  + object[key] + "" );
   }

答案 1 :(得分:2)

@VoteyDisciple已正确指出您的方法出错了。实现您的功能的另一种(更短的)方式是:



function objectToArray (object) {
  return Object.keys(object).map(function (key) {
    return key + " is " + object[key];
  });
 }

var arr = objectToArray({name: "Marcia", age: 101});
console.log(arr);