Javascript 将对象转换为数组(angularjs 和 typeahead)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26022628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:13:12  来源:igfitidea点击:

Converting object to array (angularjs and typeahead)

javascriptangularjs

提问by matenji

Let's say I have an object that looks like this: {"1": "2", "3": "4"}

假设我有一个看起来像这样的对象:{"1": "2", "3": "4"}

I don't have direct access to this data, so when I bring it in via ajax how can I convert it to an array? Like so: [{"1": "2"}, {"3": "4"}]

我无法直接访问这些数据,所以当我通过 ajax 将其引入时,如何将其转换为数组?像这样:[{“1”:“2”},{“3”:“4”}]

PS: I'm using this output data in an angular-ui typeahead which dislikes objects and only likes strings.

PS:我在一个不喜欢对象而只喜欢字符串的angular-ui typeahead中使用这个输出数据。

回答by SteveD

Here's a snippet:

这是一个片段:

var inputObj = {'1': '2', '3': '4'};
var output = [];
for (var key in inputObj) {
  // must create a temp object to set the key using a variable
  var tempObj = {};
  tempObj[key] = inputObj[key];
  output.push(tempObj);
}

console.log(output);

Hope that helps!

希望有帮助!