Rename object keys of return object [duplicate] - javascript

This question already has an answer here:
ES6/ES2015 object destructuring and changing target variable
(1 answer)
Closed 1 year ago.
Szenario
A method matter returns an object, like return {content, data}
Conflict
The second call of the method (a method from a node module) overwrites previous vars set from return.
import matter from 'gray-matter'
const test = () => {
...
const { content, data } = matter(source1)
const { content, data } = matter(source2) // this overwrites previous content, data vars
...
}
Goal / Question
Setting the return values in different named vars, like:
const { content2, data2 } = matter(source2) // like so it leads to an compiling error property content2 does not exists on type [...]
So, how can be the return values assigned to different named vars as they are named in the type?

Just use different variable names:
const { content, data } = matter(source1)
const { content: content2, data: data2 } = matter(source2)
Or don't destructure at all:
const result1 = matter(source1)
const result2 = matter(source2)
Or use an array of objects:
const results = [source1, source2].map(matter);

Related

Why is my console.log(persons.includes(newNameObject)) returning as false, when newNameObject already exists in the array? [duplicate]

This question already has answers here:
Javascript: Using `.includes` to find if an array of objects contains a specific object
(7 answers)
How to determine if Javascript array contains an object with an attribute that equals a given value?
(27 answers)
Closed 24 days ago.
I am working on a simple react app where I would like to prevent the form from adding a duplicate element to the array of objects
I have two instances of state
const [persons, setPersons] = useState([
{ name: 'Arto Hellas' }
])
const [newName, setNewName] = useState('')
a function that sets the new name upon input change
function handleNoteChange(e){
console.log(e.target.value)
setNewName(e.target.value)
}
and a function that intends to add a new element to the array upon submission of the form
function addName(e){
const newNameObject = {
name: newName
}
console.log(persons.includes(newNameObject))
e.preventDefault()
setNewName("")
if(persons.includes(newNameObject) ){
alert(`${newName} has already been added`)
}
else{
setPersons(persons.concat(newNameObject))
}
}
I have a console.log where I am checking to see if the current name I am inputing ('Arto Hellas') is already in the persons array, its saying this is false when it should be true since this is the first and only item in my state so far, not sure exactly why this is happening
It is returning false, because includes does comparison based on reference not on the value that each object holds.
To solve your use case, you have to manually iterate through each object in the array and do object comparison with the required element as show below.
function containsObject(searchElement, actualArray) {
var isObjectPresent = true;
for(var i = 0; i < actualArray.length; i++) {
if(JSON.stringify(actualArray[i]) != JSON.stringify(searchElement)) {
isObjectPresent = false;
break;
}
}
return isObjectPresent;
}
NOTE: This approach works only if the order of the properties are same

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

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?

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

What does this line of code mean? const {"intl": { formatMessage }, } = this.context [duplicate]

This question already has answers here:
Javascript object bracket notation ({ Navigation } =) on left side of assign
(5 answers)
Closed 4 years ago.
I'm new in react and I'm reading some code i found this line of code:
const {intl: { formatMessage }, } = this.context
is a const declaration but i don't understand
I know is JS ES6 but i don't understand what is it for?
How can I check the value of this const?
thanks
As people already answered. This is object destructuring
Simple example: const contact = {name: 'John', email: 'john#doe.com'}
With ES6 you can do const {email} = contact; //email = contact.email
In case you want to name the variable differently, it would be:
const {email: mailbox} = contact //equivalent to mailbox = contact.email;
Back to the original question: {intl: { formatMessage }, } = this.context
=> {formatMessage} = this.context.intl => formatMessage = this.context.intl.formatMessage
The code that you have is, actually a representation of the following code,
const formatMessage = this.context.intl.formatMessage
You can read about object destructuring to know more about it.
This simply means that this.context contains a structure similar to this
this.context = {
intl:{
formatMessage: // This has a value let's say "Hello"
},
//Other key-value pairs could be contained in the context object }
This line of code is a shorthand syntax telling you that only the formatMessage property which can be found inside "intl" should be retrieved from the large object called "this.context"

Create new object with variable key and value on one line [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 6 years ago.
I'm looking for a simple syntax to allow me to create a new object with one property and set the value of that property. Here's an example. I'd love to be able to do something all on one line.
let parent = 'jackets',
let responses = [{'color':'red', 'size':'medium'}]
let tmp = {}
tmp[parent] = responses
return tmp
Should log:
{
"jackets": [
{
'color':'red',
'size':'medium'
}
]
}
I thought I saw once that this was going to be possible in the es-spec but it doesn't work with the babel-2015 preset.
let jackets = {`${parent}`: responses}
this works for me:
*note: I have the result consoling to the console. Open console to see the results.
const responses = [{'color':'red', 'size':'medium'}]
const jackets = "jackets"
const A = {[jackets]: responses}
console.log(A)
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.min.js"></script>
0Aconst%20A%20%3D%20%7B%5BL%5D%3A%20responses%7D%0Aconsole.log(A)%0A
const jackets = {[parent]: responses}
console.log(jackets)
// gives
{"jackets":[{"color":"red","size":"medium"}]}
noted: other person got in before me.
You will need to use computed property names.
const key = 'foo';
const value = 'bar';
const foobar = {[key]: value}; // {foo: 'bar'}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names
(This works with es2015 Babel preset)

Categories