How to get the opposite property? - javascript

I have the following object with (always) 2 properties. It wil always have 2 properties. 3 properties won't be possible:
var people = {
'John': { ... },
'Peter': { ... }
}
And I have the variable var name = 'John'.
Is there a simple way to get the value of property 'Peter' when the value of name is 'John'?
Without hard-coding it with the names John en Peter. So the functionality must get the opposite property of the value in variable name

let name = 'John'; // or whatever
let names = Object.keys(people);
let otherName = names.find(n => n !== name);
people[otherName] // this gives you the value of the other name's property

Object.keys will give you an array of the property names.
filter lets you filter that array.
So:
const name = "John";
const people = {
'John': 1,
'Peter': 1
};
const [result] = Object.keys(people).filter(person => person !== name);
console.log({
result
});

I wrote a simple function, that does this. It takes a key, and an object. It returns the value of the element in the given object by the inverse key of the given key. This will only work if the object only has two keys.
var people = {
'John': { 'b':[3,4] },
'Peter': { 'a':[1,2] }
}
getInverseObjectElem = (key,object) => { // Define function 'getInverseObjectElem'
listOfObjectKeys = Object.keys(object) // Create an array of the object keys
inverseKey = listOfObjectKeys.filter(k => k != key)[0] // filter the list of keys, and get the first key that doesnt match the given key.
return object[inverseKey] // Return the value in the object, by the inverseKey
}
console.log(getInverseObjectElem('John',people))

You could try this:
for (let key in people){
if (key != name) return people[key];
}

Related

Can't get key from value within an object

I am trying to get the value associated with a key and create a new object, such as below. However when I assign the value of employeeCountryName to the object newCountryList, i get employeeCountryName returned and not "United Kingdom".
Any thoughts why this may be?
const countryList = {
"United Kingdom": "GBR"
};
const employeeCountryCode = "GBP"
const getKey = (obj, val) => Object.keys(obj).find(key => obj[key] === val);
const employeeCountryName = getKey(countryList, employeeCountryCode);
const newCountryList = {
employeeCountryName: employeeCountryCode
};
Keep in mind that when you define an object, it's keys aren't based on any other variables by default, they are just strings taken as keys. In order to tell javascript to take the value of a variable you have predefined instead of using it directly as a key, you need to add [] around them like this:
const variableName = 'keyToUse';
const object = { [variableName]: 1 } // { keyToUse: 1 }
You can use like that;
const newCountryList = {
[employeeCountryName]: employeeCountryCode
};
By the way, in your case find function couldn't find any key-value pair so it returns undefined. Because "United Kingdom" field has a GBR value and you're trying to find GBP

Convert String to Object Key Name

I'm sending different objects to a component outside, and component data varies depending on objects. I'm getting the names with the Object.key function because the keywords I send have different key. Then I want to sort by the key. For this I need to define the name I received with Object.key function. How can I do it?
upSortTable(items, val) {
//items = Object,
//val = index
let Keys = Object.keys(items[0]); // ["item_id","item_title"]
let keyname = Keys[val]; //item_id String value
//want to use in sort function as b.item_id
return items.sort(function(a, b) {
return b.keyname - a.keyname;
});
},
You'll need to use computed property:
return items.sort(function(a, b) {
return b[keyname] - a[keyname];
});
When you do a.keyname you're actually looking for the property keyname in a itself.

cannot set property of undefined in a loop

I'm doing a loop to generate array of object. I have used faker to generate fake name, but in specified iteration I want to insert my own value, in this case the person's car.
Below code I got cannot set property of car of undefined, what's wrong?
const person = []
times(2, index => {
if (index === 0) {
person[0].car = 'honda'
} else if(index ===1) {
person[1].car = 'ford'
}
person.push({
name: faker.random.name()
})
}
console.log(person)
Apart from some closing parentheses missing, you try to first access an unexisting object (person[0].car...), and create it later (person.push(...)).
Reverse the order.
let newPerson = { name: faker.random.name(), car: 'dodge' };
person.push(newPerson);
person is an empty array initially, there are no objects in it, so when trying to do person[0].car it throws error because person[0] is undefined and and you cannot set or get any property from undefined.
Instead do this
person[0] = {}
person.car = 'honda'
or
person[0] = {'car': 'honda'}

MongoDB/JS Create Object Key from String

I have a string such as :
key = "person.name.first"
Is it possible to convert that to...
{
person: {
name: {
first: '????'
}
}
}
You could write a small recursive utility function to achieve this in java script
var key = "person.name.first".split("\.");
var obj = {};
function create(o,index){
if(index > key.length-1) return;
o[key[index]] = {};
index++;
create(o[key[index-1]],index);
}
// Call the recursive function:
create(obj,0);
Then you could set the value as: person.name.first = "value";
If you would want to set the values, or dynamically set the type of each field such as an array or object, you could have an mapping array, which holds the type for each field and could be read during the creation.

Getting the object's property name [duplicate]

This question already has answers here:
How to list the properties of a JavaScript object?
(18 answers)
Closed 6 months ago.
I was wondering if there was any way in JavaScript to loop through an object like so.
for(var i in myObject) {
// ...
}
But get the name of each property like this.
for(var i in myObject) {
separateObj[myObject[i].name] = myObject[i];
}
I can't seem to find anything like it on Google. They say to pass the names of the variables with them but this is not an option for what I am trying to achieve.
Thanks for any help you can offer.
Use Object.keys():
var myObject = { a: 'c', b: 'a', c: 'b' };
var keyNames = Object.keys(myObject);
console.log(keyNames); // Outputs ["a","b","c"]
Object.keys() gives you an array of property names belonging to the input object.
i is the name.
for(var name in obj) {
alert(name);
var value = obj[name];
alert(value);
}
So you could do:
seperateObj[i] = myObject[i];
Disclaimer
I misunderstood the question to be: "Can I know the property name that an object was attached to", but chose to leave the answer since some people may end up here while searching for that.
No, an object could be attached to multiple properties, so it has no way of knowing its name.
var obj = {a:1};
var a = {x: obj, y: obj}
What would obj's name be?
Are you sure you don't just want the property name from the for loop?
for (var propName in obj) {
console.log("Iterating through prop with name", propName, " its value is ", obj[propName])
}
you can easily iterate in objects
eg: if the object is
var a = {a:'apple', b:'ball', c:'cat', d:'doll', e:'elephant'};
Object.keys(a).forEach(key => {
console.log(key) // returns the keys in an object
console.log(a[key]) // returns the appropriate value
})
for direct access a object property by position...
generally usefull for property [0]... so it holds info about the further...
or in node.js 'require.cache[0]' for the first loaded external module, etc. etc.
Object.keys( myObject )[ 0 ]
Object.keys( myObject )[ 1 ]
...
Object.keys( myObject )[ n ]
Other than "Object.keys( obj )", we have very simple "for...in" loop - which loops over enumerable property names of an object.
const obj = {"fName":"John","lName":"Doe"};
for (const key in obj) {
//This will give key
console.log(key);
//This will give value
console.log(obj[key]);
}
To get the property of the object or the "array key" or "array index" depending on what your native language is..... Use the Object.keys() method.
Important, this is only compatible with "Modern browsers":
So if your object is called, myObject...
var c = 0;
for(c in myObject) {
console.log(Object.keys(myObject[c]));
}
Walla! This will definitely work in the latest firefox and ie11 and chrome...
Here is some documentation at MDN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
IN ES5
E.G. you have this kind of object:
var ELEMENTS = {
STEP_ELEMENT: { ID: "0", imageName: "el_0.png" },
GREEN_ELEMENT: { ID: "1", imageName: "el_1.png" },
BLUE_ELEMENT: { ID: "2", imageName: "el_2.png" },
ORANGE_ELEMENT: { ID: "3", imageName: "el_3.png" },
PURPLE_ELEMENT: { ID: "4", imageName: "el_4.png" },
YELLOW_ELEMENT: { ID: "5", imageName: "el_5.png" }
};
And now if you want to have a function that if you pass '0' as a param - to get 'STEP_ELEMENT', if '2' to get 'BLUE_ELEMENT' and so for
function(elementId) {
var element = null;
Object.keys(ELEMENTS).forEach(function(key) {
if(ELEMENTS[key].ID === elementId.toString()){
element = key;
return;
}
});
return element;
}
This is probably not the best solution to the problem but its good to give you an idea how to do it.
Cheers.
As of 2018 , You can make use of Object.getOwnPropertyNames() as described in Developer Mozilla Documentation
const object1 = {
a: 1,
b: 2,
c: 3
};
console.log(Object.getOwnPropertyNames(object1));
// expected output: Array ["a", "b", "c"]
Using Object.keys() function for acquiring properties from an Object, and it can help search property by name, for example:
const Products = function(){
this.Product = "Product A";
this.Price = 9.99;
this.Quantity = 112;
};
// Simple find function case insensitive
let findPropByName = function(data, propertyName){
let props = [];
Object.keys(data).forEach(element => {
return props.push(element.toLowerCase());
});
console.log(props);
let i = props.indexOf(propertyName.toLowerCase());
if(i > -1){
return props[i];
}
return false;
};
// calling the function
let products = new Products();
console.log(findPropByName(products, 'quantity'));
When you do the for/in loop you put up first, i is the property name. So you have the property name, i, and access the value by doing myObject[i].
These solutions work too.
// Solution One
function removeProperty(obj, prop) {
var bool;
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
if (keys[i] === prop) {
delete obj[prop];
bool = true;
}
}
return Boolean(bool);
}
//Solution two
function removeProperty(obj, prop) {
var bool;
if (obj.hasOwnProperty(prop)) {
bool = true;
delete obj[prop];
}
return Boolean(bool);
}
Quick & dirty:
function getObjName(obj) {
return (wrap={obj}) && eval('for(p in obj){p}') && (wrap=null);
}

Categories

Resources