I would like to know how to fetch the keys in object contains only underscore in javascript.
I would like to get the output with text before underscore, as shown
var obj={
cn_start: "SG",
cn_end:"TH",
cn1_start:"ML",
cn1_end:"IN"
}
Expected Output
[
cn, cn1
]
I believe using reduce is better, but for better readability, I use for loop.
First, you get the keys using Object.keys, then iterate the keys finding the ones with '_' and push the prefix if it does not exists yet.
var obj={
cn_start: "SG",
cn_end:"TH",
cn1_start:"ML",
cn1_end:"IN"
}
const keys = Object.keys(obj);
let underscoreKeys = [];
keys.forEach(key => {
if(key.substring('_')){
const prefix = key.split('_')[0];
if(underscoreKeys.indexOf(prefix) < 0){
underscoreKeys.push(prefix);
}
}
});
console.log(underscoreKeys);
For an Internet Explorer compatible answer, try the following:
var obj={
cn_start: "SG",
cn_end:"TH",
cn1_start:"ML",
cn1_end:"IN"
}
var objkeys = Object.keys(obj);
var underscorekeys = [];
for(var i = 0; i < objkeys.length; i++) {
var index = objkeys[i].indexOf("_");
if(index > -1) {
var prefix = objkeys[i].substr(0, index);
if(underscorekeys.indexOf(prefix) < 0)
underscorekeys.push(prefix);
}
}
console.log(underscorekeys);
The other answers use 'arrow functions' or 'lambda functions' which is ES6 and not IE compatible.
You can grab the keys from your object using Object.keys(), then filter out all the keys which don't have an underscore in them. Next, you can .map() each key to a substring of itself by removing the underscore _ and its trailing text (using .replace(/_.+/, '')). You can then use a new Set to remove any duplicates, and Array.from to turn that set back into an array:
const obj={
cn_start: "SG",
cn_end:"TH",
cn1_start:"ML",
cn1_end:"IN"
}
const get_keys = obj =>
Array.from(new Set(Object.keys(obj).filter(k => k.includes('_')).map(k => k.replace(/_.+/, ''))));
console.log(get_keys(obj));
If you know all your keys will have an underscore in them, then you can remove the .filter().
Split the key names by '_' and add them to Set to get unique keys.
var obj = {
cn_start: "SG",
cn_end: "TH",
cn1_start: "ML",
cn1_end: "IN"
};
const keys = [...new Set(Object.keys(obj).map(key => key.split("_")[0]))];
console.log(keys);
const keysNames = Object.keys(myObj);//returns the array ['keyName','keyName'];
Related
My code:
rbx.getPlayers(539310, 1).promise.then(players => {
console.log(players)
for (var list in players.players) {
console.log(list)
var key = Object.Key(list)
console.log(Key)
}
})
What it outputs:
{ total: 9,
players:
{ AgentJay400: 65910635,
MatthewHAndreas: 49787909,
coolguysocoolroblox: 165524669,
CAMPER5155: 45422370,
Mavnkei: 69082588,
kaankerem123: 92305180,
egehan432: 120777218,
panpanaber54: 31962303,
IXTactical_CactusXI: 17451343 } }
AgentJay400
MatthewHAndreas
coolguysocoolroblox
CAMPER5155
Mavnkei
kaankerem123
egehan432
panpanaber54
IXTactical_CactusXI
Problem:
I need the number values of each user (So {AgentJay4000: 65910635} I would want the 65910635) Node.js does not seem to have Object.keys so... I have no clue how to get the number...
Node should definitely have Object.keys. If your version doesn't you should update node. When you call Object.keys you get an array in return, so you can do awesome array things like map, reduce, forEach:
Object.keys(players.players).forEach(function(key) {
console.log(key, players.players[key])
})
If you just want the number values, then map it:
Object.keys(players.players).map(function(key) {
return players.players[key]
})
Now you have an array of the numbers only.
Try like this.You can access your object value using . operator.
Suppose you have an object:
var obj={
key1:value1,
key2:value2
}
Then access values like obj.key1 or obj['key1'].
to get all the values.Use Object.values(obj);
var obj = { total: 9,
players:
{ AgentJay400: 65910635,
MatthewHAndreas: 49787909,
coolguysocoolroblox: 165524669,
CAMPER5155: 45422370,
Mavnkei: 69082588,
kaankerem123: 92305180,
egehan432: 120777218,
panpanaber54: 31962303,
IXTactical_CactusXI: 17451343 } };
var players = obj.players;
var number_values = Object.values(players);
console.log(number_values );
You can output the keys and their associated numbers by doing the following:
rbx.getPlayers(539310, 1).promise.then(players => {
console.log(players)
for (var key in players.players) {
console.log(key, ':', players.players[key])
}
})
To demonstrate how Object.keys works an alternative method of accessing the players - this does the same as the above.
rbx.getPlayers(539310, 1).promise.then(players => {
var keys = Object.keys(players.players);
for (var i = 0; i < keys.length; i++) {
let key = keys[i];
let player = players.players[key];
console.log(key, ':', players.players[key])
}
});
The mistakes you made in your attempt were you were attempting to access Object.key which was a typo for Object.keys and attempting to obtain a list of keys from a string (as a loop such as for(var key in obj) will set key to each key in obj and all object keys are strings).
I have not been able to figure out how to properly accomplish this.
I have a JS array of objects that looks like this:
[{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}]
I would like to convert this into a simple, single JS array, without any of the keys, it should look like this:
[
"09599",
"KCC",
"000027",
"Johns" ]
The IDs can be dropped entirely. Any help would be really appreciated.
Simply iterate the original array, pick the interesting keys and accumulate them in another array, like this
var keys = ['num', 'name'],
result = [];
for (var i = 0; i < data.length; i += 1) {
// Get the current object to be processed
var currentObject = data[i];
for (var j = 0; j < keys.length; j += 1) {
// Get the current key to be picked from the object
var currentKey = keys[j];
// Get the value corresponding to the key from the object and
// push it to the array
result.push(currentObject[currentKey]);
}
}
console.log(result);
// [ '09599', 'KCC', '000027', 'Johns' ]
Here, data is the original array in the question. keys is an array of keys which you like to extract from the objects.
If you want to do this purely with functional programming technique, then you can use Array.prototype.reduce, Array.prototype.concat and Array.prototype.map, like this
var keys = ['num', 'name'];
console.log(data.reduce(function (result, currentObject) {
return result.concat(keys.map(function (currentKey) {
return currentObject[currentKey];
}));
}, []));
// [ '09599', 'KCC', '000027', 'Johns' ]
You can use Object.keys() and .forEach() method to iterate through your array of object, and use .map() to build your filtered array.
var array = [{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}];
var filtered = array.map(function(elm){
var tmp = [];
//Loop over keys of object elm
Object.keys(elm).forEach(function(value){
//If key not equal to id
value !== 'id'
//Push element to temporary array
? tmp.push(elm[value])
//otherwise, do nothing
: false
});
//return our array
return tmp;
});
//Flat our filtered array
filtered = [].concat.apply([], filtered);
console.log(filtered);
//["09599", "KCC", "000027", "Johns"]
How about using map :
var data = [
{"num":"09599","name":"KCC","id":null}
{"num":"000027","name":"Johns","id":null}
];
var result = data.map(function(obj) {
return [
obj.num,
obj.name,
obj.id
];
});
I have a JavaScript Object and I'm sure the value of any key is an array (even empty in some case):
{key1:["a","b","c"],key2:["d","e","f"],key3:...}
Aside from using Underscore, is there any way to concatenate all the values of this Object (and create a new array)?
At the moment I get the keys name using Object.keys, then I loop and concatenate.
Any help is appreciated.
var obj = {key1:["a","b","c"],key2:["d","e","f"]};
var arr = Object.keys(obj).reduce(function(res, v) {
return res.concat(obj[v]);
}, []);
// ["a", "b", "c", "d", "e", "f"]
A simple approach is to get the values using Object.values() and concatenate them with [].concat.apply() in this way:
const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }
const _arr = [].concat.apply([], Object.values(_obj))
console.log(_arr)
Another similar way, is to merge Object.values() by spreading them into Array.concat() like this:
const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }
const _arr = [].concat(...Object.values(_obj))
console.log(_arr)
Also reducing each value of the Object.values() and concatenate them, you can get the same result:
const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }
const _arr = Object.values(_obj).reduce((r,c) => r.concat(c), [])
console.log(_arr)
To finish, you can also use Array.prototype.flat() over each value of the Object.values(). Just keep in mind: it's not supported on all browsers.
const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }
const _arr = Object.values(_obj).flat()
console.log(_arr)
Hope this methods could help someone out there :)
Check the array concat function
var obj = {key1:["a","b","c"],key2:["d","e","f"],key3:["g","h"]};
var resultArray = [];
for (var key in obj) resultArray = resultArray.concat(obj[key]);
alert(resultArray);
jsfiddle:
http://jsfiddle.net/qpLq11ea/
Try this:
http://jsfiddle.net/6hbp5bzo/
var arr= [];
var o={key1:["a","b","c"],key2:["d","e","f"]}
for(key in o){
if(o.hasOwnProperty(key)){
arr.push(o[key]);
}
}
alert(arr);
Very similar to this question:
Javascript: how to dynamically create nested objects using object names given by an array
Instead of calling
assign(obj, keyPath, value)
example of usage of the previously answer:
var accountinfo = {}
assign(accountinfo, ["name", "addressinfo", "zipcode"], "90210");
That will output:
accountinfo = {name: "", addressinfo: {zipcode:"90210"}};
Now, I'd like to support arrays... in the above example, I'd like to support multiple addressinfo per account. I'd like to say:
assign(accountinfo, ["name", "addressinfo[1]", "zipcode"], "90210");
The result would be:
accountinfo = {name: "", addressinfo: [{},{zipcode:"90210"}]}
var regex = /\[([0-9]+)\]/ will show me the # inside the brackets, but I'm not sure how I'd have to iterate through each element in the array to make sure it exists (and create it if it doesn't).. and the difficult part, support this for each array element submitted as part of the function (I'd like to say :
assign(accountinfo, ["family", "name[3]", "addressinfo[1]", "zipcode"], "90210");
Edit:
Figured it out.
function assign(obj, keyPath, value) {
keyPath = keyPath.split(‘.’);
lastKeyIndex = keyPath.length - 1;
var re = /^(.+?)\[*(\d+)*\]*$/;
for (var i = 0; i < lastKeyIndex; i++) {
key = keyPath[i];
var ind;
var middle = re.exec(key);
key = middle[1];
ind = middle[2];
if (ind) {
if (!(obj[key]))
obj[key] = [];
if (!(obj[key][ind]))
obj[key][ind] = {};
}
if (!(key in obj))
obj[key] = {};
if (ind)
obj = obj[key][ind];
else
obj = obj[key];
}
obj[keyPath[lastKeyIndex]] = value;
}
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 8 years ago.
If I have an object such that
var object = function(key,text)
{
this.key = key;
this.text = text;
}
And create an array of these objects
var objArray = [];
objArray[0] = new object('key1','blank');
objArray[1] = new object('key2','exampletext');
objArray[2] = new object('key3','moretext');
is there a way that I can retrieve only one of the properties of all of the objects in the array? For example:
var keyArray = objArray["key"];
The above example doesn't return set keyArray to anything, but I was hoping it would be set to something like this:
keyArray = [
'key1',
'key2',
'key3']
Does anyone know of a way to do this without iterating through the objArray and manually copying each key property to the key array?
This is easily done with the Array.prototype.map() function:
var keyArray = objArray.map(function(item) { return item["key"]; });
If you are going to do this often, you could write a function that abstracts away the map:
function pluck(array, key) {
return array.map(function(item) { return item[key]; });
}
In fact, the Underscore library has a built-in function called pluck that does exactly that.
var object = function(key,text) {
this.key = key;
this.text = text;
}
var objArray = [];
objArray[0] = new object('key1','blank');
objArray[1] = new object('key2','exampletext');
objArray[2] = new object('key3','moretext');
var keys = objArray.map(function(o,i) {
return o.key;
});
console.log(keys); // ["key1", "key2", "key3"]
JS Bin Example
http://jsbin.com/vamey/1/edit
Note that older browsers may not support map but you can easily do this with a for loop:
var keys = [];
for (var i = 0; i < objArray.length; i++) {
keys.push(objArray[i].key);
}
JS Bin Example
http://jsbin.com/redis/1/edit
You would want to do something like this:
objArray.map(function (obj) { return obj.key; });
Here is a JSFiddle to demo: http://jsfiddle.net/Q7Cb3/
If you need older browser support, you can use your own method:
JSFiddle demo: http://jsfiddle.net/Q7Cb3/1/
function map (arr, func) {
var i = arr.length;
arr = arr.slice();
while (i--) arr[i] = func(arr[i]);
return arr;
}
Well something has to iterate through the elements of the array. You can use .map() to make it look nice:
var keys = objArray.map(function(o) { return o.key; });
You could make a function to generate a function to retrieve a particular key:
function plucker(prop) {
return function(o) {
return o[prop];
};
}
Then:
var keys = objArray.map(plucker("key"));
Really "objArray" is an array that have 3 objects inside, if you want list of keys, you can try this:
var keys = [];
for(a in objArray) {
keys.push(objArray[a].key);
}
You have in var keys, the three keys.
Hope that helps! :)