This question already has answers here:
Javascript get Object property Name
(4 answers)
Closed 7 years ago.
I have a Json object in following format
MyJsonObject= {
'Animal': ['Lion', 'Tiger', 'Elephant'],
'Human': ['Man', 'Woman']
};
I want to get the key as return type if we pass value to function. Eg If I pass value =Man, function should return Human as return type. similarly, If I passed Tiger as value than I want to get Animal as return value.
Any help will be appreciated
Hi the snippet bellow should work.
You can try here http://jsfiddle.net/xtdqodzk/1/
MyJsonObject= {
'Animal': ['Lion', 'Tiger', 'Elephant'],
'Human': ['Man', 'Woman']
};
function find(value){
for(var prop in MyJsonObject ){
if(MyJsonObject.hasOwnProperty(prop)){
for(var i =0 ;i<MyJsonObject[prop].length;i++){
if(MyJsonObject[prop][i] === value){
return prop;
}
}
}
}
}
alert(find('Man'));
You can try to modify Object prototype
Object.prototype.findKey = function(value) {
for (var key in this) {
if (this.hasOwnProperty(key)) {
for (var i = 0; i < this[key].length; i++) {
if (this[key][i] === value) {
return key;
}
}
}
}
}
var MyJsonObject = {
'Animal': ['Lion', 'Tiger', 'Elephant'],
'Human': ['Man', 'Woman']
};
console.log(MyJsonObject.findKey('Man'));
The advantage of doing this way is if you have another json object you can call .findKey function on that object as well since all objects inherit functions and properties from Object.prototype object (prototypal inheritance).
Related
This question already has answers here:
One liner to flatten nested object
(19 answers)
Closed 3 months ago.
good night, I'm having trouble merging an object inside another
my object currently.
{
"id":7,
"name":"Pedroo",
"email":"pedro#hotmail.com",
"cognitoSub":"9162b350-d19db1b3f",
"phoneNumber":"+5521997221764",
"photo":null,
"createdAt":"2022-10-21T14:48:36.000Z",
"updatedAt":"2022-10-21T14:48:36.000Z",
"Account":{
"userId":7
}
}
and I would like to leave it in a single object
example:
{
"id":7,
"name":"Pedroo",
"email":"pedro#hotmail.com",
"cognitoSub":"9162b350-d19db1b3f",
"phoneNumber":"+5521997221764",
"photo":null,
"createdAt":"2022-10-21T14:48:36.000Z",
"updatedAt":"2022-10-21T14:48:36.000Z",
"userId":7
}
Try this method
const flattenObj = (ob) => {
// The object which contains the
// final result
let result = {};
// loop through the object "ob"
for (const i in ob) {
// We check the type of the i using
// typeof() function and recursively
// call the function again
if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) {
const temp = flattenObj(ob[i]);
for (const j in temp) {
// Store temp in result
result[j] = temp[j];
}
}
// Else store ob[i] in result directly
else {
result[i] = ob[i];
}
}
return result;
};
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 5 years ago.
I have an object and I want to remove all values except the one that matches a particular key. For example, I could do this:
function remove(obj, key) {
var value = obj[key]
var ret = {}
ret[key] = obj[key]
obj = ret
}
Or I could iterate:
for (var k in obj) {
if (k != key) {
delete obj[k]
}
}
But I'm wondering if there's a better way. Creating a temporary variable and iterating over the entire object both seem unnecessary. My initial attempt was:
obj = {
key: obj[key]
}
But that resulted in an object with a key of key.
You can indeed achieve what you described without using temporary variables.
function remove(obj, key) {
return Object.assign({}, { [key] : obj[key]});
}
You can just create a new object with [key]:obj[key].
var obj = {
"a":1,
"b":2
};
var key = "a";
function filterByKey(object, key) {
return Object.create({[key]:obj[key]});
}
function filterByKey2(object, key) {
return {[key]:obj[key]};
}
console.log(filterByKey(obj, key));
console.log(filterByKey2(obj, key));
This question already has answers here:
How to set object property (of object property of..) given its string name in JavaScript?
(16 answers)
Closed 8 years ago.
I've read this existing question on stackoverflow.
My target is to set a property on a "nested Property and set a new Value (without eval!):
What i have is a dynamic string as example : “A.B.C”
And a JSON Object:
var obj ={
A: {
B: {
C: 23
C1: {}
}
}
}
Now i want to access this property and set it:
If the string has a fixed amount of properties i can just write:
obj[prop1][prop2][prop3] = 42
What would be the way to make this dynamic, so when passing “A.B” the object at B is replaced?
Something like this will work..
var str = "A.B.C";
var obj ={
A: {
B: {
C: 23,
C1: {}
}
}
};
updateObj(obj,str,10);
function updateObj(obj,str,val){
var tok = str.split(".");
var update = function(obj, index){
if (index < tok.length){
if ( !obj.hasOwnProperty(tok[index])){
obj[tok[index]] = {};
}
if (index == tok.length-1){
obj[tok[index]] = val;
}
update(obj[tok[index]],++index);
}
}
update(obj,0);
}
console.log(obj);
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 8 years ago.
Say I call following function:
var query = makeQuery("email", "foo#bar.com");
The implementation I have is:
makeQuery = function (key, value) {
return { key: value};
}
The object I end up with is: {"key": "foo#bar.com"}, which is obviously wrong. I would like to obtain {"email": "foo#bar.com"} instead. I tried setting it like so:
makeQuery = function (key, value) {
return { JSON.stringify(key): value};
}
... but I get a "SyntaxError: Unexpected token ." I've also thought of using toString() and even eval(), without success. So my problem is to be able to set the property of the object returned in makeQuery() using its real value, that is, pick up the value of 'key', not setting the property with the 'key' literal.
Thanks for the help.
Create the object first and then use the square bracket syntax so you can set the property using the value of key:
makeQuery = function (key, value) {
var query = {};
query[key] = value;
return query;
};
For variable keys in objects, use
var obj[key] = value
So then it becomes:
function makeQuery(key, value) {
var obj = {};
obj[key] = value;
return obj;
}
define an object..
makeQuery = function (key, value) {
var o = {};
o[key] = value;
return o;
}
This question already has answers here:
Re-associating an object with its class after deserialization in Node.js
(4 answers)
Closed 6 years ago.
i have a question to deserialize JSON text to an javascript object, i test jquery and yui library, i have this class:
function Identifier(name, contextId) {
this.name = name;
this.contextId = contextId;
}
Identifier.prototype.setName = function(name) {
this.name = name;
}
Identifier.prototype.getName = function() {
return this.name;
}
Identifier.prototype.setContextId = function(contexId) {
this.contextId= contexId;
}
Identifier.prototype.getContextId = function() {
return this.contextId;
}
and i have this JSON:
{
"Identifier": {
"name":"uno",
"contextId":"dos"}
}
I want to the parse create an Identifier object, my problem is that this sentences:
var obj = jQuery.parseJSON('{"Identifier": { "name":"uno","contextId":"dos"}}');
or
var obj2 = JSON.parse('{"Identifier": { "name":"uno","contextId":"dos"}}');
Dont work, the var obj and obj2 aren't an Identifier object, how can i parse this?
Thanks
This question is not the duplicate, because it was made 5 years before than the question that Michael marks as duplicated
You could create a function that initializes those objects for you. Here's one I quickly drafted:
function parseJSONToObject(str) {
var json = JSON.parse(str);
var name = null;
for(var i in json) { //Get the first property to act as name
name = i;
break;
}
if (name == null)
return null;
var obj = new window[name]();
for(var i in json[name])
obj[i] = json[name][i];
return obj;
}
This creates an object of the type represented by the name of the first attribute, and assigns it's values according to the attributes of the object of the first attribute. You could use it like that:
var identifier = parseJSONToObject('{"Identifier": { "name":"uno","contextId":"dos"}}');
console.log(identifier);
Live example