简体   繁体   English

如何在Javascript中将对象转换为数组

[英]how to convert object to array in javasscript

I need to convert the object to an array, this is my object, I need to convert an array 我需要将对象转换为数组,这是我的对象,我需要转换数组

{value1: prop1, value2: prop2, value3: prop3};

expected output 预期产量

["value1": prop1, "value2": prop2, "value3":prop3]

I have tried my code below 我已经在下面尝试了我的代码

var obj = {value1: prop1, value2: prop2, value3: prop3};
var arr = [];
for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
             arr.push(key + ':' + obj[key]);
    }
};

getting wrong ouput please see below 输出错误,请参阅下文

["value1:prop1", "value2:prop2", "value3:prop3"]

expected out like below 预期如下

["value1": prop1, "value2": prop2, "value3":prop3]

Your approach is good, this .push and object definition is just not working in Javascript as you would expect: 您的方法很好,这个.push和对象定义在Javascript中不起作用,正如您期望的那样:

 var obj = {value1: 'aa', value2: 'bb', value3: 'cc'}; var arr = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { const newObj = {}; newObj[key] = obj[key]; arr.push(newObj); } }; console.log(arr); 

Your expected output is not a valid javascript syntax. 您的预期输出不是有效的JavaScript语法。 There are a couple of ways to go about this, you could convert your object to a 2d array where the inline array holds the key and value of each field in the object. 有两种解决方法,您可以将对象转换为2d数组,其中内联数组保存对象中每个字段的键和值。

var obj = {value1: prop1, value2: prop2, value3: prop3};
var arr = [];
for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
         arr.push([key, obj[key]]);
    }
};

Output 输出量

[['value1', prop], ['value2', prop2], ['value3', prop3]]

If you're using javascript es2017, you can achieve the above result using Object.entries(obj) 如果您使用的是javascript es2017,则可以使用Object.entries(obj)实现以上结果

This method should not be possible as arrays do not have keys like in php, the keys in JS arrays are always numbers. 由于数组没有像php中那样的键,因此此方法应该不可能,JS数组中的键始终是数字。

Arrays should look like this: 数组应如下所示:

let array = ["value1", "value2", "value3"]

And contained values are called with indexes: 包含的值通过索引调用:

// Just the value
array[0]

// Logging the value
console.log(array[0])

Assuming you want to get an array of objects with single properties, you could take the entries and map new objects with a computed property name . 假设要获取具有单个属性的对象数组,则可以获取条目并使用计算出的属性名映射新对象。

 var object = { value1: 'prop1', value2: 'prop2', value3: 'prop3' }, array = Object .entries(object) .map(([key, value]) => ({ key, value })); console.log(array); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM