How to change key in JS object
Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
-
Marius
- Posts: 107
How to change key in JS object
I have a question: i want to change keys into a JavaScript object if their value is number, for example, I have the following object:
Code: Select all
const order = {
wine : 100,
vodka : 200,
beer : 300,
whisky : "not in stock"
};
I want to get this result:
Code: Select all
const order = {
is_nr_100 : 100,
is_nr_200 : 200,
is_nr_300 : 300,
whisky : "not in stock"
};
Admin
To change a key into a JavaScript object, you need to clone the value with the new key, and then you delete the old key in the object.
Code: Select all
const order = {
wine : 100,
vodka : 200,
beer : 300,
whisky : "not in stock"
};
function changeKey(obj) {
for (var prop in obj) {
if (typeof obj[prop] === 'number') {
obj['is_nr_' + obj[prop]] = obj[prop]
delete obj[prop]
}
}
}
changeKey(order);
console.log(order);
Similar Topics
-
Change the max upload size in XAMPP
PHP - MySQL
First post
Pleassant Marplo, hope all things are okey ?
I have a question, I think I have server problem with uploading maximal upload-file (mb) is to less I...
Last post
Marplo in once thanks for the great suport
-
Get the length of a JSON object in JS
JavaScript - jQuery - Ajax
First post
I have converted a database table into a JSON object.
This is in essence a two-dimensional array, with each record being the first dimension, which...
Last post
You can use Object.keys to get the list of keys in the Object as an array and then get the length from it:
Object.keys(act_obj_array).length;