Turning an array into array of objects but cannot run function [duplicate] - javascript

This question already has answers here:
Why can I not use the spread operator on a class function?
(3 answers)
Copy prototype for inheritance?
(2 answers)
Closed 25 days ago.
Alright, I must be missing something here. I have an object:
export class Country {
id: number = 0
name: string = ''
getNamePlusBob() {
return this.name + 'bob'
}
}
And I get the data from an API in an array, then pass it to the browser.
Once i have the data I want to turn the array into an array of objects of type 'Country'.
So I made this function (not sure if Hydrate is the correct term here?):
function hydrateArray(data, entity) {
let returnArray = []
console.log(data)
data.forEach((row) => {
const object = entity;
for (const [key, value] of Object.entries(row)) {
if(Object.hasOwn(object, key)) {
object[key] = value
} else {
console.log('Key not found in entity', key)
}
}
console.log(object.getNamePlusBob())
returnArray.push({...object})
})
return returnArray
}
const countries = hydrateArray(countryData, new Country())
In the console.log in the function, I can run the getNamePlusBob() and it returns the name plus bob. However, on the returned array countries, I cannot:
console.log(countries[0].getNamePlusBob())
TypeError: countries[0].getNamePlusBob is not a function
Why not? It was inside the hydrateArray function, why cant I run it outside?

Related

Search Key/Value Inside Nested Objects (JavaScript) [duplicate]

This question already has answers here:
Recursive function does not return specified value
(2 answers)
Search recursively for value in object by property name
(13 answers)
Closed 2 years ago.
I'm trying to find a object value inside a nested object, this object has a lot o level's and this specific object value that i want it's not always in the same level inside the object.
What i'm trying to do is:
//ArrayofCoordinates it's the array of the objects that i want to search my value inside of each of this objects.
let coordinatesToAddArray = [];
arrayOfCoordinates.map(coordinateObject => {
let coordinateData = findObjectNested(coordinateObject, 'tagName', 'text'); //'tagName' it's the key that i'm looking for and 'text' it's the value of the 'tagName' key that i'm looking for.
if(coordinateData) {
coordinatesToAddArray.push(coordinateData);
}
});
//This is the recursive function that i created to search inside the object for the specific value and return him, but all i get from the return of this function it's a undefined.
function findObjectNested(entireObj, keyToFind, valueToFind) {
if(entireObj && entireObj[keyToFind] === valueToFind) {
return entireObj;
} else {
if(entireObj['children'].length > 0) {
entireObj['children'].map(objectsOfChildren => {
findObjectNested(objectsOfChildren, keyToFind, valueToFind);
});
}
}
}
I know that the recursive function it's working because when i replace the "return entireObj" to "console.log(entireObj)" i can see the object that i'm looking for, but when i'm trying to return this object all i get it's a undefined.
I believe that this has something to do with the recursive function.
Anyone can help me with any tips about how to solve this problem?
Thank you so much.

Create object mapping via dot walking which is a string [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 2 years ago.
I make a call to downstream and receive a response something like
// for sake of ease, let's call this variable as resp
{
"data":{
"abc": {
"value":"Hi there",
"timestamp":"xxxxxxxxxx"
}
}
}
I then need to access resp.data.abc.value but the problem is that I've to do it dynamically (i.e. the data.abc.value part is coming from database)
So the flow of my program is something like this:
/*
(a) Make a REST call
(b) Receive the response, assign it to a variable named "resp"
(c) Grab the dot walking path from db
(d) DB result will be "data.abc.value" and type will be a string
(e) Figure out a way to split the DB result and apply it on the "resp" variablevalue
*/
I've tried using .split() and iterating through a loop but it's getting quite messy and complex to understand.
You could use .reduce for splited dot paths, tricky path here is to handle non-existed path, but it could be solved by using default value
const getByDotPath = (path = "", object = {}) => {
return path
.split(".")
.reduce((iteratee = {}, p) => iteratee[p], object)
}
const getByDotPath = (path = "", object = {}) => {
return path
.split(".")
.reduce((iteratee = {}, p) => iteratee[p], object)
}
const resp = {
data: {
abc: {
value: "Hi there",
timestamp: "xxxxxxxxxx",
},
},
}
console.log(getByDotPath("data.abc.value", resp))
console.log(getByDotPath("data.abc.value.def", resp))
You can use lodash's get:
const data = _.get(resp, "data.abc.value");

Getting the value of a specific key in an object through a function [duplicate]

This question already has answers here:
How can I get the index of an object by its property in JavaScript?
(22 answers)
Closed 4 years ago.
As an exercise, I am trying to write a function called getValue() which takes two parameters, obj and key.
This is unrelated to getting an index of an object by its property.
The function should pass in the name of an object (obj) and the name of an object property (key), the return the value associated with that property. If there is no value (that is, the property does not exist in the object), getValue() should return undefined. As long as the named property does exist, the function should return its associated value.
I wrote a function that works but only if the property is named key. Which of course is not what I had in mind.
function getValue(obj, key) {
this.obj = {};
this.key = obj.key;
const val = function() {
return obj.key;
};
return val();
}
var theObject = {nokey: 'my_value'};
var output = getValue(theObject, 'nokey');
console.log(output);
// --> 'should return 'my_value' but
// but returns undefined
Since you're passed the object itself, just access the property with bracket notation:
function getValue(obj, key) {
return obj[key];
}
var theObject = {nokey: 'my_value'};
console.log(getValue(theObject, 'nokey'));
var object2 = {foo: 'bar'};
console.log(getValue(object2, 'baz'));

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

Set an object property by using its value [duplicate]

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

Categories