I need a function to get the keys from objects, and the entries from arrays, like so:
_key(["x", "y", "z"]); // ["x", "y", "z"];
_key({ a: "x", b: "y", c: "z" }); // ["a", "b", "c"];
Is there a built-in way to do this, and if not, what's the shortest possible method?
You can first test it if it's array with Array.isArray()
function _key(data) { return Array.isArray(data) ? data : Object.keys(data); } console.log(_key(["x", "y", "z"])) console.log(_key({ a: "x", b: "y", c: "z" }))
If you need for example to pass multiple parameters, object and arrays you can use rest parameter syntax and map()
to return one array.
function _key(...data) { return [].concat(...data.map(e => Array.isArray(e) ? e : Object.keys(e))) } console.log(_key(["x", "y", "z"], { a: "x", b: "y", c: "z" }, {z: 1}))
function values(object) {
return (object instanceof Array) ? object : Object.keys(object);
}
You could test if it is an array or not and return either the values or the keys of the object. I works with ES6 only.
function _key(data) { return Object[['keys', 'values'][+Array.isArray(data)]](data); } console.log(_key(["x", "y", "z"])) console.log(_key({ a: "x", b: "y", c: "z" }))
Thanks for all the answers, guys! Here's what I did:
_key = function (_) {
let u = [].slice.call(_), v = Object.values(_).length;
return u.length >= v ? toString.call(_) == "Array" ? _ : u : keys(_);
};
This works on arrays, pseudo-arrays (like arguments), objects, and pseudo-objects (like window)
It works by using some weird behavior, which can be tested with this snippet:
_test = function (x, y) { console.log(y + ":", [].slice.call(x).length + "-" + Object.values(x).length); }; console.log("Input: AB"); _test(["x"], "Array"); _test({ x: "" }, "Object"); _test(document.querySelectorAll("div"), "Pseudo-Array"); _test(document, "Pseudo-Object");
<div></div>
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.