简体   繁体   中英

Return two separate arrays from an object in JavaScript

I need to complete the keysAndValues function so that it takes an object and returns the keys and values as separate arrays. For example:

keysAndValues({k: 11, l: 12, m: 13}) // should return [['k', 'l', 'm'], [11, 12, 13]]

I have already tried: http://jsfiddle.net/marcusdei/ppfh5fpa/4/

Try this

 function keysAndValues(data){ var keys = Object.keys(data), values = keys.map(function (key) { return data[key]; }); return [keys, values]; } console.log(keysAndValues({k: 11, l: 12, m: 13})); 

Object.keys - The Object.keys() method returns an array of a given object's own enumerable properties

.map - The map() method creates a new array with the results of calling a provided function on every element in this array.

Update

There is new method .values which was added to Object ,

 function keysAndValues(data){ return [Object.keys(data), Object.values(data)]; } console.log(keysAndValues({k: 11, l: 12, m: 13})); 

Object.values - the method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop

Try:

 function keyValues(obj, keys){ return [keys = Object.keys(obj), keys.map(function(k){return obj[k]})] } var result = keyValues({k: 11, l: 12, m: 13}); document.write(JSON.stringify(result)) 

The old-fashioned way, defining two arrays and pushing the keys and values into them.

function keysAndValues(obj) {
    var keys = [], values = [];
    for (var p in obj) {
        keys.push(p);
        values.push(obj[p]);
    }
    return [keys, values];
}

JSPerf says this has the better performance by far .

 function keysAndValues(obj) { var keys = []; var value = []; for (key in obj) { keys.push(key); value.push(obj[key]); } return [keys,value] } console.log(keysAndValues({ k: 11, l: 12, m: 13 })); 

Object.entries gets you halfway there, returning an array of key-value` pairs.

Example:

obj = { k: 11, l: 12, m: 13 }
Object.entries(obj); // [["k", 11], ["l", 12], ["m", 13]]

From here you can reduce this array into separate arrays by pushing the keys into one array and the values into the other.

 const keysAndValues = (obj) => Object.entries(obj).reduce( ([keys, values], [key, value]) => [keys.concat(key), values.concat(value)], [[], []] ); const res = keysAndValues({ k: 11, l: 12, m: 13 }); console.log(JSON.stringify(res)); // [["k", "l", "m"], [11, 12, 13]]

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