对象(具有属性)的转换数组返回0长度 [英] Converted Array from Object (with properties) returns 0 length

查看:112
本文介绍了对象(具有属性)的转换数组返回0长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的javascript文件中包含以下代码:

I have this code in my javascript file:

var items = {
    first: 'Item 1',
    second: 'Item 2',
    third: 'Item 3'
};
var arr = Array.prototype.slice.call(items);

console.log(arr.length);

我想将一个对象转换成一个数组.我的问题是,当对象转换为数组时,为什么当对象已具有属性时javascript返回0?我希望有人能帮助我,如果有人不介意,我希望在不使用jQuery的情况下对其进行纠正.

I want to convert an object into an array. My question is, when the object was converted into array, why does javascript return 0 when the object already has properties? I hope someone could help me and if anyone wouldn't mind, I want it to be corrected without using jQuery.

推荐答案

您可以使用

You can use Object.entries() to create an array of arrays of properties, values from original object or an array of objects reflecting properties, values of original object.

Object.entries()方法返回给定对象自己的数组 可枚举属性[key, value]对,其排序顺序与 由for...in循环提供(区别是for-in循环 枚举原型链中的属性.

The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

var items = {
    first: 'Item 1',
    second: 'Item 2',
    third: 'Item 3'
};

var arr = Object.entries(items);

console.log(arr);

var arr1 = Object.entries(items)
           .map((value, index) => {
              return {[value.shift()]: value.pop()}                    
           });

console.log(arr1);

这篇关于对象(具有属性)的转换数组返回0长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆