简体   繁体   中英

Convert object literal notation to array

I used a literal as a dictionary, but a third party binding tool only takes arrays.

This is one way, is there a better one?

var arr = [];
$.each(objectLiteral, function () { arr.push(this); });

I think there is nothing wrong with your solution.

This is a shorter one:

var arr = $.map(objectLiteral, function (value) { return value; });

Your method is fine, clear and readable. To do it without jQuery, use the for (..in..) syntax:

var arr = [];
for (prop in objectLiteral) {
  arr.push(objectLiteral[prop]);
}

In vanilla JS...

If we want to convert an object literal

var obj = {
 species: 'canine',
 name: 'Charlie',
 age: 4
}

into an array of arrays

[['species', 'canine'], ['name', 'Charlie'], ['age', 4]]

here is one way

function objToArr(obj){
  var arr = [];

  for (var key in obj){
    arr.push([key, obj[key]]);
  }
  return arr;
}
const objectLiteral = { hell: 'devil' };

const ver1 = Object.keys(objectLiteral); // ['hell']
const ver2 = Object.values(objectLiteral); // ['devil']
const ver3 = Object.entries(objectLiteral); // [['hell', 'devil']]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/keys https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/entries

In ES2017 you can now use Object.entries and with ES6 destructuring support you can use the resulting array pretty nice, example

Object.entries(objectLiteral).filter(([key, value]) => !!value).map(([key, value]) => key)

Gets you all properties with a value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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