how to unify an object from objects [duplicate] - javascript

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;
};

Related

How to save path to specific property of object in variable [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Fastest way to flatten / un-flatten nested JavaScript objects
(17 answers)
Closed 3 years ago.
Let's say I have object like this:
let object = {
inner: {
inInner: {
a: 5
}
}
}
and I want to store path to property a in variable so I can access it like this:
object[pathToProperty]
Thank you for any suggestions
You can import Lodash, and use it like this:
var path = 'inner.inInner';
var value = _.get(object, path);
You could take a Proxy and address the inner key.
let object = { inner: { inInner: { a: 5 } } },
proxy = new Proxy(object, {
find: function (o, k) {
var value;
if (k in o) return o[k];
Object.values(o).some(v => {
if (v && typeof v === 'object') {
return value = this.find(v, k);
}
});
return value;
},
get: function(obj, prop) {
return prop in obj ?
obj[prop] :
this.find(obj, prop);
}
});
console.log(proxy.a);

JavaScript: remove all but 1 key from an object [duplicate]

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));

Get key from value in Json [duplicate]

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).

Convert array to object properties JavaScript [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 7 years ago.
I have an object:
{
messages: {
foo: {
bar: "hello"
},
other: {
world: "abc"
}
}
}
I need a function:
var result = myFunction('messages.foo.bar'); // hello
How to create this function?
Thanks
I've written such a set of utility functions here:
https://github.com/forms-js/forms-js/blob/master/source/utils/flatten.ts
There's also the Flat library:
https://github.com/hughsk/flat
Either should suit your needs. Essentially it boils down to something like this:
function read(key, object) {
var keys = key.split(/[\.\[\]]/);
while (keys.length > 0) {
var key = keys.shift();
// Keys after array will be empty
if (!key) {
continue;
}
// Convert array indices from strings ('0') to integers (0)
if (key.match(/^[0-9]+$/)) {
key = parseInt(key);
}
// Short-circuit if the path being read doesn't exist
if (!object.hasOwnProperty(key)) {
return undefined;
}
object = object[key];
}
return object;
}

How to do a deep search of object from a given string [duplicate]

This question already has answers here:
Convert string in dot notation to get the object reference [duplicate]
(6 answers)
Closed 8 years ago.
I would like to split the str (dot seperated) and look inside an object tree, if the values exist.
To keep it simple, I have just create a simple object, but I would like it to be a deep search.
I just need the logic not necessary a working code, just a direction on what I need to do inside the exists to, check recursebly if person.name.first does exist with a boolean value true || false to be returned as the final answer.
var str = "person.name.first";
var arr = {
person: {
name: {'first':true ,'last' : true },
age : true
}
}
function exists(){
...
}
exists(str,arr);//true === exists, false === does not exist
Just try with:
function exists(str, arr) {
var parts = str.split('.');
for (var i = 0; i < parts.length; i++ ) {
if (arr.hasOwnProperty(parts[i])) {
arr = arr[parts[i]];
} else {
return false;
}
}
return true;
}

Categories