How to convert object keys to upper case - javascript

I would like to transform lowercase key to uppercase key. But finding my try not works.
what would be the correct approach?
here is my try:
var obj = {
name: "new name",
age: 33
}
const x = Object.assign({}, obj);
for (const [key, value] of Object.entries(x)) {
key = key.toUpperCase();
}
console.log(x);
Live Demo

With
key = key.toUpperCase();
Reassigning a variable will almost never do anything on its own (even if key was reassignable) - you need to explicitly to mutate the existing object:
var obj = {
name: "new name",
age: 33
}
const x = {};
for (const [key, value] of Object.entries(obj)) {
x[key.toUpperCase()] = value;
}
console.log(x);
You could also use reduce, to avoid the external mutation of x:
var obj = {
name: "new name",
age: 33
}
const x = Object.entries(obj).reduce((a, [key, value]) => {
a[key.toUpperCase()] = value;
return a;
}, {});
console.log(x);

Related

Unstring an object property name javascript

I have an object similar to this:
const obj = {
id: 1,
name: {
"english-us": "John",
"english-uk": "John",
"italian-eu": "Giovanni",
},
};
I want to transfrorm every property name that is a string into a non-string one, like this:
const obj = {
id: 1,
name: {
english_us: "John",
english_uk: "John",
italian_eu: "Giovanni",
},
};
I can't modify the original object. I get it from an axios request.
You could use regex with stringify
let output = JSON.parse(JSON.stringify(obj).replace(/"(.*?)":.*?,?/g,
key=>key.replace(/\-/g, `_`)));
Output
console.log(JSON.stringify(output, null, 4));
/*
{
"id": 1,
"name": {
"english_us": "John",
"english_uk": "John",
"italian_eu": "Giovanni"
}
}*/
If you can copy the object, you could check this solution for declaring the attributes:
link
There are a few ways of achieving this. This example has a function that converts the key on every iteration of the name entries. A new names object is updated with these properties, and is later folded into a new object along with the existing properties of the original object.
const obj = {
id: 1,
name: {
"english-us": "John",
"english-uk": "John",
"italian-eu": "Giovanni",
},
};
const convert = (key) => key.replace('-', '_');
const updatedName = {};
for (const [key, value] of Object.entries(obj.name)) {
updatedName[convert(key)] = value;
}
const newObj = { ...obj, name: updatedName };
console.log(newObj);
You can convert object to JSON and convert back.
const obj = {
id: 1,
name: {
"english-us": "John",
"english-uk": "John",
"italian-eu": "Giovanni",
},
};
console.log(JSON.parse(JSON.stringify(obj)))
Two ways to clone the object and rename all keys from its name property
const obj = {
id: 1,
name: {
"english-us": "John",
"english-uk": "John",
"italian-eu": "Giovanni",
},
};
// clone obj
const myObj = window.structuredClone ?
structuredClone(obj) : JSON.parse(JSON.stringify(obj));
// rename all keys in myObj.name
Object.keys(myObj.name).forEach(key => {
myObj.name[key.replace(/\-/g, `_`)] = myObj.name[key];
delete myObj.name[key];
});
console.log(myObj.name.english_us);
// obj is untouched
console.log(obj.name[`english-us`]);
// myObj.name[`english-us`] does not exist
console.log(myObj.name[`english-us`]);
// alternative: clone and rename in one go
const myObjClone = {
...obj,
name: Object.fromEntries(
Object.entries(obj.name)
.reduce( (acc, [k, v]) =>
[ ...acc, [ k.replace(/\-/g, `_`), v ] ] , [] ) )
};
console.log(myObjClone.name.italian_eu);
// obj is untouched
console.log(obj.name[`italian-eu`]);
// myObjClone.name[`italian-eu`] does not exist
console.log(myObjClone.name[`italian-eu`]);

Js obj with key name defined by Object.keys

var c = {
'aa-bb': [{ a: 1, v: 2}],
'cc-xz': [{ c: 2}]
}
console.log(Object.keys(c))
I need to create an object, whose keys (the name) must be from Object.keys.
For each key name an object of type array must be defined as below.
Can you give me a hand?
result:
const res = {
'aa-bb': Array(number).fill(0),
'cc-xz': Array(number).fill(0)
};
var c = {
'aa-bb': [{
a: 1,
v: 2
}],
'cc-xz': [{
c: 2
}]
}
const keys = Object.keys(c);
let res = {},
number = 5;
keys.forEach(key => res[key] = Array(number).fill(0));
console.log(res);
Map the keys, and create pairs of [key, array], and convert back to an object using Object.fromEntries():
const fn = (obj, arrLengh) =>
Object.fromEntries(
Object.keys(obj)
.map(key => [key, Array(arrLengh).fill(0)])
);
const c = {"aa-bb":[{"a":1,"v":2}],"cc-xz":[{"c":2}]};
const result = fn(c, 5);
console.log(result);

How to transform Array to Object?

What is the best way to transform an array like this:
const arr = [
{ name: 'Bob' },
{ name: 'Ben' }
{ name: 'Cole' }
{ name: 'Mary' }
{ name: 'Travis' }
]
to an object like:
const obj = {
'B': ['Bob', 'Ben'],
'C': ['Cole'],
'M': ['Mary'],
'T': ['Travis']
}
Using only vanilla JS
You can use array#reduce. Iterate through each object of your array and then extract out the first letter and add names corresponding to it.
const arr = [{name: 'Bob'}, {name: 'Ben'}, {name: 'Cole'}, {name: 'Mary'}, {name: 'Travis'}],
result = arr.reduce((r,{name}) => {
r[name[0]] = r[name[0]] || [];
r[name[0]].push(name);
return r;
},{});
console.log(result);
Vanilla JS you say? Here you go
let nil = x => x === undefined;
let empty = ([h]) => nil(h);
let first = ([h]) => h;
let last = ([h, ...t]) => empty(t) ? h : last(t);
let map = ([h, ...t], f) => nil(h) ? [] : [f(h), ...map(t, f)];
let reduce = ([h, ...t], f, i) => nil(h) ? i : reduce(t, f, f(i, h));
let tab = (a, f) => map(a, x => [x, f(x)]);
let push = (a, x) => nil(a) ? [x] : [...a, x];
let groupBy = (a, f) => _groupBy(tab(a, f));
let _groupBy = ka => reduce(ka, (g, [x, k]) => ({...g, [k]: push(g[k], x)}), {});
///
const arr = [{ name: 'Bob' },{ name: 'Ben' },{ name: 'Cole' },{ name: 'Mary' },{ name: 'Travis' }]
z = groupBy(map(arr, x => x.name), first)
console.log(z)
No built-ins!
I created an array where the key is the first letter of the name using the reduce function and restructuring the 'name' from the objects. If the key exists in the array the name is pushed (using spread operator). Else, it creates the key with only one element.
const arr = [
{ name: 'Bob' },
{ name: 'Ben' },
{ name: 'Cole' },
{ name: 'Mary' },
{ name: 'Travis' }
];
const obj = arr.reduce((res, {name})=>{
res[name[0]] = res[name[0]] ? [...res[name[0]],name] : [name];
return res;
}, {});
console.log(obj);
I think this thread is missing a non functional answer, so here it is:
const obj = {};
for(const {name} of arr)
(obj[name[0]] || (obj[name[0]] = [])).push({name});
let obj = {};
arr.forEach( e => {
const name = e.name;
if (!obj[name.charAt(0)]) obj[name.charAt(0)] = [];
obj[name.charAt(0)].push(name);
})
I'm generating a new object and adding to it news keys based in the first char of the name values (only if the key hasn't been already added).
Then, I add each value to the key that corresponds.

JavaScript - Altering keys when criteria met

I want to write a function that takes an array of objects as an argument. If an object in the array contains the key "name," I want to change that key to "title." I then want to return an updated version of the array of objects with all of the keys changed.
This is my attempt at doing this. It's not doing what I want it to.
const people = [{age: 32},{name: 'bob'},{name: 'jack', age: 3}];
function nameToTitle(arr){
let result = [];
for(let i = 0; i < arr.length; i++){
if(arr[i].name){
let newObj = {};
for(let x in arr[i]){
if(arr[i][x] === 'name'){
newObj['title'] = arr[i][x];
}
else {
newObj[x] = arr[i][x];
}
}
result.push(newObj);
}
else {
result.push(arr[i])
}
}
return result;
}
console.log(nameToTitle(people));
This above code returns this:
[ { age: 32 }, { name: 'bob' }, { name: 'jack', age: 3 } ]
=> undefined
It doesn't change the name key to "title."
The code below should work for your use case. Note that I've changed people to a mutable variable (not a const any more). Essentially all this does is iterate over each dictionary in your array, if it finds a dictionary with the "name" key it sets a "title" key with the same value and then deletes the "name" key.
var people = [{age: 32}, {name: 'bob'}, {name: 'jack', age: 3}];
for (var i = 0; i < people.length; i++) {
if (people[i].hasOwnProperty("name")) {
people[i]["title"] = people[i]["name"];
delete people[i]["name"];
}
}
console.log(people);
You are very close, your if-condition is checking the value of your object rather than the key. So all you need to do is change:
if(arr[i][x] === 'name') // 'bob' === 'name' for {name: 'bob'}
to:
if(x === 'name') // 'name' === 'name' for {name: 'bob'}
Because the value of x in for(let x in arr[i]) is the key value that you are iterating.
const people = [{age: 32},{name: 'bob'},{name: 'jack', age: 3}];
function nameToTitle(arr){
let result = [];
for(let i = 0; i < arr.length; i++){
if(arr[i].name){
let newObj = {};
for(let x in arr[i]){
if(x === 'name'){
newObj['title'] = arr[i][x];
}
else {
newObj[x] = arr[i][x];
}
}
result.push(newObj);
}
else {
result.push(arr[i])
}
}
return result;
}
console.log(nameToTitle(people));
you can map over the objects in the array and modify objects that have the name property as shown below
peoples.map(people => {
if(people.hasOwnProperty('name')) {
let title = people.name;
delete people.name;
return Object.assign({}, people, {title: title});
}
return people;
})
const people = [{age: 32},{name: 'bob'},{name: 'jack', age: 3}];
// Copy all properties. If key is 'name' change it to 'title'
const copyObjectWithTitle = obj =>
Object.keys(obj).reduce((objAcc, key) => {
const value = obj[key];
return Object.assign({}, objAcc, key === 'name' ? { title: value} : { [key]: value });
}, {})
// Map over the list. If the object has the key 'name' return a copy with the key 'title'
const nameToTitle = (list) => list.map(obj => obj.hasOwnProperty('name') ? copyObjectWithTitle(obj) : Object.assign({}, obj))
const updatedPeople = nameToTitle(people);
I would do this, if you just want to change the name property to title:
function nameToTitle(objsArray){
var s = objsArray.slice(), a; // make a copy
for(var i in s){
a = s[i];
if(a.name){
s[i].title = a.name; delete s[i].name;
}
}
return s;
}
var objsArray = [{age:32},{name:'bob'},{name:'jack', age:3}];
console.log(nameToTitle(objsArray));
This might get downvoted a bit, but just for fun :]
const people = [{age: 32}, {name: 'bob'}, {name: 'jack', age: 3}];
const result = eval(JSON.stringify(people).replace(/\bname\b/g, 'title'));
console.log(result);

Changing the case of JavaScript object keys

I have following object.
var obj = [{
Address1: "dd",
Address2: "qww",
BankAccNo: "44",
BankBranchCode: "44",
BloodGrp: "A+"
},
{
Address1: "dd",
Address2: "qww",
BankAccNo: "44",
BankBranchCode: "44",
BloodGrp: "A+"
}];
How can I make all of the keys uppercase?
I want to be able to access values like this : - obj[0].ADDRESS1
obj = obj.map( function( item ){
for(var key in item){
var upper = key.toUpperCase();
// check if it already wasn't uppercase
if( upper !== key ){
item[ upper ] = item[key];
delete item[key];
}
}
return item;
});
http://jsfiddle.net/07xortqy/
Loop over all the properties in the object (with for in)
Use .toUpperCase() to get the uppercase version of the property name
Copy the value from the original property to the uppercase version
delete the original property
For anyone looking for a solution working with objects, arrays, and nested objects or arrays:
// rename function depending on your needs
const capitalizeKeys = (obj) => {
const isObject = o => Object.prototype.toString.apply(o) === '[object Object]'
const isArray = o => Object.prototype.toString.apply(o) === '[object Array]'
let transformedObj = isArray(obj) ? [] : {}
for (let key in obj) {
// replace the following with any transform function
const transformedKey = key.replace(/^\w/, (c, _) => c.toUpperCase())
if (isObject(obj[key]) || isArray(obj[key])) {
transformedObj[transformedKey] = capitalizeKeys(obj[key])
} else {
transformedObj[transformedKey] = obj[key]
}
}
return transformedObj
}
const t = {
test1: 'hello',
test2: {
aa: 0,
bb: '1',
cc: [ 3, '4', 'world']
},
test3: [{
aa: 5,
bb: '6'
}, {
cc: [ 'hello', 'world', 7 ]
}
]
}
console.log(JSON.stringify(capitalizeKeys(t)))
(this function is to be adapted since I only had to capitalize the first letter, and there is no need for the helper functions to be nested)
$.each(obj, function(i, parent) {
$.each(parent, function(key, record) {
parent[ key.toUpperCase() ] = record[key]; //rename key
delete parent[key]; //delete old key
});
});
let obj = [
{ Address1: "dd",Address2: 'qww',BankAccNo: 44,BankBranchCode: 44,BloodGrp: 'A+' },
{ Address1: "dd",Address2: 'qww',BankAccNo: 44,BankBranchCode: 44,BloodGrp: 'A+' }
];
const uppercaseKeys = (elem) => {
let newObject = {}
Object.keys(elem).reduce( (acc, key, allKeys) => {
acc[key.toUpperCase()] = elem[key]
delete elem[key]
return acc
}, elem)
return newObject
}
obj.forEach( o => uppercaseKeys )
console.log(obj)
You can now also use Object.fromEntries() in combination with Object.entries() - have a look at the Object transformations section.
const obj2 = obj1.map(item => Object.fromEntries(Object.entries(item).map(([key, val]) => [
key.toUpperCase(),
val
])));
I've detailed the steps below:
// Iterate through each item in array
const obj2 = obj1.map(item => {
// Object.entries() method returns array of object's own enumerable string-keyed property [key, value] pairs,
// in the same order as that provided by a for...in loop
const entries = Object.entries(item);
// Convert keys to uppercase
const uppercaseEntries = entries.map(([key, val]) => [
key.toUpperCase(),
val
]);
// Object.fromEntries() method transforms a list of key-value pairs into an object.
return Object.fromEntries(uppercaseEntries);
});`
https://jsfiddle.net/buj5y32x/3/
For wider support, you are better off using Object.keys() with Array.reduce().
const obj2 = obj1.map(item =>
Object.keys(item).reduce((accumulator, key) => {
// accumulator is the new object we are creating
accumulator[key.toUpperCase()] = item[key];
return accumulator;
}, {})
);
https://jsfiddle.net/qf81ezsy/
You could just loop through them and add new entries?
for (index in obj) {
for (key in obj[index]) {
obj[index][key.toUpperCase()] = obj[key];
}
}

Categories

Resources