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'];
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.