Change all properties of an object - javascript

Is there a way to change all properties of an object to a given value, for example to 0? Will it work with nested objects?
I guess it's a noob question, but i started messing around with js only few days ago.
EDIT:
basically it looks like this:
var obj1 = {
obj11: {
a11: 1
b11: 2
c11: 321
},
obj12: {
a12: 31
b12: 65
c12: 8776
}
}
All those values are affected by some other functions. I wanted to make a "reset" function that would set all those values to 0. My expected output is:
{
obj11: {
a11: 0
b11: 0
c11: 0
},
obj12: {
a12: 0
b12: 0
c12: 0
}
}

let obj1 = {
obj11: {
a11:1,
b11:2,
c11:321,
},
obj12: {
a12:31,
b12:65,
c12:8776,
},
};
// Declare a function with a single argument o.
function reset(o) {
// Loop through all of the properties of the argument object o
for([key, value] of Object.entries(o)) {
const t = typeof value;
switch(t) {
// If the current property has an object value, handle that recursively.
case 'object': reset(value); break;
// If the current property has a numeric value, set the value to 0.
case 'number': o[key] = 0; break;
// Otherwise print some status information.
default: console.log('The property '+key+'is of an unhandled type ('+t+').');
}
}
}
reset(obj1);
// Print the result for convenience.
console.log(JSON.stringify({obj1}));

One way to do this is to take advantage of JSON.stringify(). Using its replacer argument, you can specify how each value should be transformed. This method will also recursively traverse your object, allowing you to change all values. As this function converts your object to a string, you'll need to convert it back using JSON.parse():
const obj1 = { obj11: { a11: 1, b11: 2, c11: 321 }, obj12: { a12: 31, b12: 65, c12: 8776 } };
const res = JSON.parse(JSON.stringify(obj1, (key, value) => Object(value) === value ? value : 0));
console.log(res);
The above uses an arrow function, which gets passed in a key and a value. This will be called for every key/value in your object. The value that you return from the arrow function is the new resulting value in the new object. In this case, that value is the is 0 when the value isn't an object, otherwise, if it is an object, we just return the original object.
Note: If you have an object type that isn't serializable (such as a function) as one of your values, then this method will remove that key-value pair.
If your object has a consistent structure and doesn't contain infinitely nested objects, you might find it more straightforward to loop over the keys of your obj1 (obj11 and obj12) using a for..in loop, and then the keys of the inner objects which you can obtain by using the currently looped on key from your outer loop:
const obj1 = { obj11: { a11: 1, b11: 2, c11: 321 }, obj12: { a12: 31, b12: 65, c12: 8776 } };
const res = {};
for(const key in obj1) {
res[key] = {};
for(const innerKey in obj1[key]) {
res[key][innerKey] = 0;
}
}
console.log(res);
Finally, you could use a recursive approach, where you use a function to loop the entries (a [[key, value], ...] pair array) of your object, with .map() to convert every value to a 0. You can then use Object.fromEntries() to build your object back together from the entries array. If you encounter an object as one of your values, you can recall this function to apply the same logic to the nested value:
const obj1 = { obj11: { a11: 1, b11: 2, c11: 321 }, obj12: { a12: 31, b12: 65, c12: 8776 } };
const changeVals = (obj, newVal) =>
Object.fromEntries(Object.entries(obj).map(
([key, val]) =>
!Array.isArray(val) && Object(val) === val && typeof val === "object"
? [key, changeVals(val, newVal)]
: [key, newVal]
)
);
console.log(changeVals(obj1, 0));

Related

How to check if an object has other than specific properties

I have an object obj which has n number of possible properties
lets say some of them are known,
const someKnownProps = ["props.abc", "xyz"]; // or more
I want to know if obj has other than known properties in it.
To clarify:
obj can look like this:
obj = {
props: {
abc: {
def: 1
},
ghi: {
jkl: 2
}
},
xyz: 3
}
Doing Object.keys only return first level children,
in this case it will return props not props.abc
You can use Object.keys to get all keys and filter the keys which aren't included in the someKnownProps array.
const obj = {
"props.abc": 1,
"xyz": 2,
"three": 3,
"four": 4,
}
const someKnownProps = ["props.abc", "xyz"]; // or more
const unknownKeys = Object.keys(obj).filter(key => !someKnownProps.includes(key))
console.log(unknownKeys)
There are two (unrelated) tasks involved in this question:
Traversal of an object's properties
Comparison of a set of traversed object properties to a list of strings representing dot-notation-formatted object property accessors
While I'm sure the former has been previously discussed on SO, I'll provide an implementation of such an algorithm below in order to address the details of this question.
This is essentially a specific case of recursion where each cycle starts with these inputs:
an object
a dot-notation-formatted path
a Set of existing such paths
The code below includes inline comments explaining what's happening, and there are some console.log statements at the end to help you visualize some example results based on the data in your question. If something is unclear after reviewing the code, feel free to leave a comment.
'use strict';
/** #returns whether value is a non-null, non-array object */
function isObject (value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
/** #returns the enumerable (optionally including inherited) keys of an object */
function getKeys (obj, includeInherited = false) {
if (!includeInherited) return Object.keys(obj);
const keys = new Set();
let o = obj;
while (o !== null) {
for (const key of Object.keys(o)) keys.add(key);
o = Object.getPrototypeOf(o);
}
return [...keys];
}
/**
* #returns an array of strings representing all traversible branches
* of child objects, each formatted as a combined path of dot-notation
* property accessors
*/
function findObjectPaths (
obj,
{
includeInherited = false,
currentPath = '',
paths = new Set(),
skipReturn = false,
} = {},
) {
for (const key of getKeys(obj, includeInherited)) {
// Append the current dot-notation property accessor
// to the existing path of this object:
const path = `${currentPath}.${key}`;
// Add it to the set:
paths.add(path);
const o = obj[key];
// Recurse if the child value is an object:
if (isObject(o)) {
findObjectPaths(o, {
includeInherited,
currentPath: path,
paths,
skipReturn: true,
});
}
}
// If this is not a sub-cycle (it's the top-level invocation), then convert
// the set to an array and remove the first "." from each string
if (!skipReturn) return [...paths].map(p => p.slice(1));
}
// Use:
const obj = {
props: {
abc: {
def: 1,
},
ghi: {
jkl: 2,
},
},
xyz: 3,
};
let someKnownProps = ['props.abc', 'xyz'];
let objectPaths = findObjectPaths(obj);
let hasOtherProps = objectPaths.some(path => !someKnownProps.includes(path));
console.log(hasOtherProps); // true
// An example of all of the paths in the object above:
someKnownProps = [
'props',
'props.abc',
'props.abc.def',
'props.ghi',
'props.ghi.jkl',
'xyz',
];
objectPaths = findObjectPaths(obj);
hasOtherProps = objectPaths.some(path => !someKnownProps.includes(path));
console.log(hasOtherProps); // false
// Finally, comparing the results of inherited vs non-inherited enumeration:
const objWithoutOwnProps = Object.create({
props: {
abc: {
def: 1,
},
ghi: {
jkl: 2,
},
},
xyz: 3,
});
console.log(
'Non-inherited props:',
findObjectPaths(objWithoutOwnProps),
);
console.log(
'Inherited props:',
findObjectPaths(objWithoutOwnProps, {includeInherited: true}),
);
Similar to what Mina said:
let obj = {one: 1, two: 2, three: 3};
let knownKeys = ['one', 'two'];
for (let key in obj) {
if (!knownKeys.includes(key)) {
console.log(key);
}
}

How to merge an object inside another object

I don't know if the question is right, but I want to do the following, I want the properties of "variable" to become part of the variable day.
The object being as follows: {seg: 60, min:1, dias: 7, semana: 1}
Remaining the object of the following way: Take into consideration that the object inside the object could be anyone and it does not have to be the property "variable" for what I would like to make it dynamic, reason why an arrangement like delete dia.variable and later to merge would not serve me.
With the code that I show you I have only obtained that the result is: {seg: 60, min:1, variable:{dias: 7, semana: 1}, dias: 7, semana: 1}
Any ideas on how I could do it more efficiently, and above all, do it.
const dia = {seg: 60, min:1, variable:{dias: 7, semana: 1}}
let varia = {}
let newDia = {}
const processJson = () => {
Object.entries(dia).map(([name, value]) => {
if(typeof(value) === 'object'){
varia = value
newDia = {...dia, ...variable}
}
})
}
processJson()
This is a universal method for flatting any object with 2 levels deep. It uses the array reduce method and the Object.keys() function:
const dia = { seg: 60, min: 1, variable: {dias: 7, semana: 1} }
function flatObject(o) {
return Object.keys(o).reduce((result, key) => {
// If there is a nested object, flat the object
if (typeof o[key] === 'object' && ! Array.isArray(o[key]) && o[key] !== null) {
for (const inKey in o[key]) {
result[inKey] = o[key][inKey];
}
}
// Just copy the value
else {
result[key] = o[key];
}
// Return accumulator
return result;
}, {});
}
console.log(flatObject(dia))
Start of by using a destructuring assignement to extract the seg, min and variable properties from the dia object.
const { seg, min, variable } = dia;
Then create a new object in which you set the seg and min properties with the destructured properties. For the variable property, use the spread syntax to place the properties of variable inside the same object.
const result = {
seg,
min,
...variable
};
const dia = {
seg: 60,
min: 1,
variable: {
dias: 7,
semana: 1
}
};
const { seg, min, variable } = dia;
const result = {
seg,
min,
...variable
};
console.log(result);

How to modify each value of a nested object?

How can I multiply every nested value of this object by X (e.g. 0.5)?
const myObject = {
base: {
serving: {
size: 100
}
},
fat: {
acids: {
monoUnsaturatedFattyAcids: 12
polyUnsaturatedFattyAcids: 3
saturatedFattyAcids: 2
},
}
}
The object is sometimes nested up to 10 levels deep.
You could define a generator that will provide an iterator over every nested key/value pair (together with the nested object), so that you can do what you want with it inside a for loop:
function * iter(obj) {
for (let [key, value] of Object.entries(obj)) {
if (Object(value) !== value) yield [obj, key, value];
else yield * iter(value);
}
}
// demo
const myObject = {
base: {
serving: {
size: 100
}
},
fat: {
acids: {
monoUnsaturatedFattyAcids: 12,
polyUnsaturatedFattyAcids: 3,
saturatedFattyAcids: 2
},
}
};
for (let [obj, key, value] of iter(myObject)) {
if (typeof value === "number") obj[key] *= 0.5; // multiply by 0.5
}
// The object has been mutated accordingly
console.log(myObject);
function modifyValues(obj) {
for (let key in obj) {
if (typeof obj[key] === "object") {
modifyValues(obj[key]);
}else {
obj[key] = obj[key] * 0.5;
}
}
return obj;
}
console.log(modifyValues({
"a": 5,
"b": {
"c": 10
},
"d": {
"e": 15,
"f": {
"g": 20
}
}
}))
As suggested here's an explanation:
You can try something like a function that recursively iterates through the properties of an object and depending on said property its type, multiply or call our recursive function again.
These are the steps the function takes:
We use the Object.keys method to get an array containing all property names as strings of our object
We iterate through our keys array
for every key we check if obj[key] its value is either a number or something else.
note about obj[key]: by using square braces you can access properties of an object by passing a string. e.g obj['base'] is equivalent to obj.base
if it's type is indeed number, multiply obj[key] by 0.5! Don't forget to actually assign the value to the property.
if it ain't a number, call the function again, but this time we use the object stored in obj[key].
e.g. when you pass myObject to the function, the first key will be base, obj.base contains an object, so we call recursiveMultiplication(obj.base) and the cycle continues.
until every recursiveMultiplication call runs out of keys to iterate through.
When all is said and done, the original object should contain mutated values.
If you don't wish to mutate you should clone the object using something like rfdc. using {...spread} won't cut it for nested objects.
const myObject = {
base: {
serving: {
size: 100
}
},
fat: {
acids: {
monoUnsaturatedFattyAcids: 12,
polyUnsaturatedFattyAcids: 3,
saturatedFattyAcids: 2
}
}
};
const recursiveMultiplication = (obj) => {
Object.keys(obj).forEach(key => typeof obj[key] === "number" ? obj[key] = obj[key] * 0.5 : recursiveMultiplication(obj[key]))
return obj;
};
console.log(recursiveMultiplication(myObject));
I think the best is to use a library to ease the traverse of the nested object.
const _ = require('lodash')
const myObject = {
base: {
serving: {
size: 100
}
},
fat: {
acids: {
monoUnsaturatedFattyAcids: 12,
polyUnsaturatedFattyAcids: 3,
saturatedFattyAcids: 2
},
}
}
const newObjValue = _.cloneDeepWith(myObject, x => typeof x === 'number'? x*0.5: undefined)
console.log(newObjValue)
Here is quick solution. I have not added cases for arrays. need to add them if you expect arrays at the top level or nested inside.
const myObject = {
base: {
serving: {
size: 100
}
},
fat: {
acids: {
monoUnsaturatedFattyAcids: 12,
polyUnsaturatedFattyAcids: 3,
saturatedFattyAcids: 2
},
}
}
function isArray ( obj ) {
return isObject(obj) && (obj instanceof Array);
}
function isObject ( obj ) {
return obj && (typeof obj === "object");
}
function recursiveMultiplyNumberFields(myObject, X){
//Assuming that at the top level, what you pass on is a dictionar object. If it could be arrays as well, need to handle more cases
for (key in myObject){
if (isNaN(myObject [key])==false){
myObject[key] = X*myObject[key];
}
else if(isArray(myObject [key])){
/*not taken care as of now. Need to do if ararys are expected inside*/
}
else if(typeof myObject [key] === 'object' && myObject [key] !== null){
recursiveMultiplyNumberFields(myObject [key],X)
}
else{
//not a number and not a object. So need not do anything
}
}
}
console.log("Before mult",myObject);
recursiveMultiplyNumberFields(myObject,5);
console.log("After mult",myObject);

_.assign only if property exists in target object

My need is to do something like an _.assign, but only if the target object already has the property being assigned. Think of it like the source objects may have some properties to contribute, but also some properties that I don't want to mix in.
I haven't ever used _.assign's callback mechanism, but tried the following. It 'worked', but it still assigned the property to the dest object (as undefined). I don't want it to assign at all.
_.assign(options, defaults, initial, function (destVal, sourceVal) {
return typeof destVal == 'undefined' ? undefined : sourceVal;
});
I wrote the following function to do this, but wondering if lodash already has something baked in that is more elegant.
function softMerge (dest, source) {
return Object.keys(dest).reduce(function (dest, key) {
var sourceVal = source[key];
if (!_.isUndefined(sourceVal)) {
dest[key] = sourceVal;
}
return dest;
}, dest);
}
You could take just the keys from the first object
var firstKeys = _.keys(options);
Then take a subset object from the second object, taking only those keys which exist on the first object :
var newDefaults = _.pick(defaults, firstKeys);
Then use that new object as your argument to _.assign :
_.assign(options, newDefaults);
Or in one line :
_.assign(options, _.pick(defaults, _.keys(options)));
Seemed to work when I tested it here : http://jsbin.com/yiyerosabi/1/edit?js,console
Here is a immutable deep version, I call it "merge that retains the shape", in TypeScript that uses lodash:
function _mergeKeepShapeArray(dest: Array<any>, source: Array<any>) {
if (source.length != dest.length) {
return dest;
}
let ret = [];
dest.forEach((v, i) => {
ret[i] = _mergeKeepShape(v, source[i]);
});
return ret;
}
function _mergeKeepShapeObject(dest: Object, source: Object) {
let ret = {};
Object.keys(dest).forEach((key) => {
let sourceValue = source[key];
if (typeof sourceValue !== "undefined") {
ret[key] = _mergeKeepShape(dest[key], sourceValue);
} else {
ret[key] = dest[key];
}
});
return ret;
}
function _mergeKeepShape(dest, source) {
// else if order matters here, because _.isObject is true for arrays also
if (_.isArray(dest)) {
if (!_.isArray(source)) {
return dest;
}
return _mergeKeepShapeArray(dest, source);
} else if (_.isObject(dest)) {
if (!_.isObject(source)) {
return dest;
}
return _mergeKeepShapeObject(dest, source);
} else {
return source;
}
}
/**
* Immutable merge that retains the shape of the `existingValue`
*/
export const mergeKeepShape = <T>(existingValue: T, extendingValue): T => {
return _mergeKeepShape(existingValue, extendingValue);
}
And a simple test to see how I vision such merge should work:
let newObject = mergeKeepShape(
{
a : 5,
// b is not here
c : 33,
d : {
e : 5,
// f is not here
g : [1,1,1],
h : [2,2,2],
i : [4,4,4],
}
},
{
a : 123,
b : 444,
// c is not here
d : {
e : 321,
f : 432,
// g is not here
h : [3,3,3],
i : [1,2],
}
}
);
expect(newObject).toEqual({
a : 123,
// b is not here
c : 33,
d : {
e : 321,
// f is not here,
g : [1,1,1],
h : [3,3,3],
i : [4,4,4]
}
});
I used seamless-immutable myself in the test, but didn't see a need to put it in this answer.
I hereby place this in the Public Domain.
Another way to accomplish this is by combining _.mapObject with _.has
_.mapObject(object1, function(v, k) {
return _.has(object2, k) ? object2[k] : v;
});
Explanation:
Traverse all key/value pairs of object1 using _.mapObject
Using _.has, check if property name k also exists in object2.
If it does, copy the value assigned to key object2's k back to object1, else, just return the existing value of object1 (v).
Plunkr
Following #svarog's answer I came up with this (lodash version 4.17.15):
const mergeExistingProps = (target, source) => _.mapValues(target, (value, prop) => _.get(source, prop, value));
I recently have the same need in my personal project, I need to fill the value from one object(SOURCE) to another object(TARGET) but don't expand its property. Also, some additional requirements should be met:
Any property with a null value in the source will not update to the target;
Any value from the source can be updated into target if such property in target has null value.
The property that holds an array in the target will be loaded based on data from the source, but all entries of the array will remain the same as the target array (so an empty array in the target will not get any data since the item has no property)
Property of the target holding a 2-d array (array has another array as its item) will not be updated, since the meaning of merging two 2-d arrays with a different shape is not clear to me.
Below is an example (Detailed explained in the code):
Assume you have a resume object holding all the data about you, you want to fill the data into the company's application form (also an object). You want the result to have the identical shape of the application form since the company doesn't care about other things, then you can think your resume is SOURCE and the application form is TARGET.
Note that the "additional" field in TARGET is null, which means anything can be updated here based on SOURCE data (As rule #2)
The console output is in JSON format, copy it to some JSON to JS-OBJ converter such as
https://www.convertsimple.com/convert-json-to-javascript/
to have a better view
const applicationForm = {
name: 'Your Name',
gender: 'Your Gender',
email: 'your#email.com',
birth: 0,
experience: [ // employer want you list all your experience
{
company: 'Some Company',
salary: 0,
city: ['', '', ''], // list all city worked for each company
}
],
language: { // employer only care about 2 language skills
english: {
read: false,
write: false,
speak: 'Speak Level'
},
chinese: {
read: false,
write: false,
speak: 'Speak Level'
}
},
additional: null // add anything you want the employer to know
}
const resume = {
name: 'Yunfan',
gender: 'Male',
birth: 1995,
phone: '1234567',
email: 'example#gmail.com',
experience: [
{
company: 'Company A',
salary: 100,
city: ['New York', 'Chicago', 'Beijing'],
id: '0001',
department: 'R&D'
},
{
company: 'Company B',
salary: 200,
city: ['New York'],
id: '0002',
department: 'HR'
},
{
company: 'Company C',
salary: 300,
city: ['Tokyo'],
id: '0003',
}
],
language: {
english: {
read: true,
write: true,
speak: 'Native Speaker'
},
chinese: {
read: true,
write: false,
speak: 'HSK Level 3'
},
spanish: {
read: true,
write: true,
speak: 'Native Speaker'
}
},
additional: {
music: 'Piano',
hometown: 'China',
interest: ['Cooking', 'Swimming']
}
}
function safeMerge(source, target) {
// traverse the keys in the source object, if key not found in target or with different type, drop it, otherwise:
// 1. Use object merge if the value is an object (Can go deeper inside the object and apply same rule on all its properties)
// 2. Use array merge if value is array (Extend the array item from source, but keep the obj format of target)
// 3. Assign the value in other case (For other type, no need go deeper, assign directly)
for (const key in source) {
let value = source[key]
const targetValueType = typeof target[key]
const sourceValueType = typeof value
// if key not found in target or type not match
if (targetValueType === 'undefined' || targetValueType !== sourceValueType) {
continue // property not found in target or type not match
}
// for both type in object, need additional check
else if (targetValueType === 'object' && sourceValueType === 'object') {
// if value in target is null, assign any value from source to target, ignore format
if (target[key] === null) {
target[key] = source[key]
}
// if value in target is array, merge the item in source to target using the format of target only if source value is array
else if (Array.isArray(target[key]) && Array.isArray(value)) {
target[key] = mergeArray(value, target[key])
}
// if value in target is 'real' object (not null or array)', use object merge to do recurring merge, keep target format
else if (!Array.isArray(target[key])){
if (!Array.isArray(value) && value !== null) {
safeMerge(value, target[key])
}
}
}
// if target value and source value has same type but not object, assign directly
else if (targetValueType === sourceValueType) {
target[key] = value
}
}
}
function mergeArray(sourceArray, targetArray) {
// the rule of array merge need additional declare, assume the target already have values or objects in save format in the property<Array>,
// otherwise will not merge item from source to target since cannot add item property,
// NOTE: the item in target array will be totally overwrite instead of append on the tail, only the format will be keep,
// so the lenth of this property will same as source, below is a example:
// target = [{a: 1, b: 2}, {a: 3, b: 4}] // Must in same format, otherwise the first one will be standard
// source = [{a: 5, b: 6, c: 7}]
// mergeArray(source, target) => [{a: 5, b: 6}] // use format of target, but data from source
// double check both of values are array
if (!Array.isArray(sourceArray) || !Array.isArray(targetArray)) {
return
}
// if target array is empty, don't push data in, since format is empty
if (targetArray.length === 0) {
return
}
let resultArray = [] // array to save the result
let targetFormat = targetArray[0]
let targetArrayType = typeof targetArray[0]
// assign value from source to target, if item in target array is not object
if (targetArrayType !== 'object'){
sourceArray.forEach((value) => {
// assign value directly if the type matched
if (targetArrayType === typeof value) {
resultArray.push(value)
}
})
}
// if the item in target is null, push anything in source to target (accept any format)
else if (targetArray[0] === null) {
sourceArray.forEach((value) => {
resultArray.push(value)
})
}
// if the item in target is array, drop it (the meaning of merge 2-d array to a 2-d array is not clear, so skip the situation)
else if (!Array.isArray(targetArray[0])){
// the item is a 'real' object, do object merge based on format of first item of target array
sourceArray.forEach((value) => {
safeMerge(value, targetFormat) // data in targetFormat keep changing, so need to save a independent copy to the result
resultArray.push(JSON.parse(JSON.stringify(targetFormat)))
})
}
else {
console.log('2-d array will be skipped')
}
// replace the value of target with newly built array (Assign result to target array will not work, must assign outside)
return resultArray
}
safeMerge(resume, applicationForm)
console.log(JSON.stringify(applicationForm))

Is there any way to use a numeric type as an object key?

It seems that when I use a numeric type as a key name in an object, it always gets converted to a string. Is there anyway to actually get it to store as a numeric? The normal typecasting does not seem to work.
Example:
var userId = 1;
console.log( typeof userId ); // number
myObject[userId] = 'a value';
console.dir(myObject);
Dir Output:
{
'1': 'a value'
}
What I want is this:
{
1: 'a value'
}
Advice?
No, this is not possible. The key will always be converted to a string. See Property Accessor docs
Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.
> var foo = {}
undefined
> foo[23213] = 'swag'
'swag'
> foo
{ '23213': 'swag' }
> typeof(Object.keys(foo)[0])
'string'
In an object, no, but I have found Map extremely useful for this application. Here is where I have used it for numeric keys, a key-based event.
onKeydown(e) {
const { toggleSidebar, next, previous } = this.props;
const keyMapping = new Map([
[ 83, toggleSidebar ], // user presses the s button
[ 37, next ], // user presses the right arrow
[ 39, previous ] // user presses the left arrow
]);
if (keyMapping.has(e.which)) {
e.preventDefault();
keyMapping.get(e.which)();
}
}
Appears to be by design in ECMA-262-5:
The Property Identifier type is used to associate a property name with a Property Descriptor. Values of the Property Identifier type are pairs of the form (name, descriptor), where name is a String and descriptor is a Property Descriptor value.
However, I don't see a definite specification for it in ECMA-262-3.
Regardless, I wouldn't attempt to use non-strings as property names.
you can use, Map if you want different datatype as keys
const map1 = new Map();
map1.set(1,3)
map1.set('1','string')
// expected output: 3
console.log(map1.get(1)) //output 3;
console.log(map1.get('1')) //output 'string';
Here is the solution. Please tell me the environmental setups if this is not working
const screens = {
"768": "large",
"200": "small"
}
const keys = Object.keys(screens).map(key => parseInt(key))
// OR Number(key)
console.log(keys) // Output [200, 768]
Do we need something like this?
var userId = 1;var myObject ={};
console.log( typeof userId ); // number
myObject[userId] = 'a value';
console.dir(myObject);
Console:
Object
1
:
"a value"
You can't, but you can always convert keys to a numbers
const data = { 15: "value", name: "Apple" };
const result = Object.keys(data) // get keys as an array
.map((item) => {
return parseInt(item); // convert to integer number
})
.filter((item) => !isNaN(item)); // remove non number elements
console.log(result); //Output: [15]
const a = {
'1': 'a value'
}
//by using a + before any string value it will convert(parse) that into a number
const b = Object.key(a);
console.log(+b); //parse
console.log(typeof b); //number
Per Mozilla:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax[Spread syntax]1
let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };
const merge = ( ...objects ) => ( { ...objects } );
let mergedObj1 = merge (obj1, obj2);
// Object { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } }
let mergedObj2 = merge ({}, obj1, obj2);
// Object { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }
Just order the items before hand and you should get the result you want.
So for your case:
const merge = (...objects) => ({...objects});
//An object with numeric keys
const values = ["a value", "another value", "and another value"];
let merged = merge(...values);
console.log(merged);
You can try this:
arr = {}
function f(a,b,c) {
arr = arguments
}
f("*","#","_")
console.log(arr)
//returns Object { 0: "*", 1: "#", 2: "_" }```
In JavaScript, numerical strings and numbers are interchangeable, so
myObject[1] == myObject['1']
If you really want number to be the key for an object, you might want an array (i.e. created with new Array() or []).

Categories

Resources