How can I replace an item in an array with an object? - javascript

album.songs = [1234545, 43524];
const replaced = album.songs.map( e => { e = Object.assign({}, { _id : 123 }) } );
Output: undefined
My problem is that I would like to replace my items in 'songs' array with a specific object. It works with strings or numbers but not with objects.

Some notes:
With map, you return the object you want the new array to contain. Assigning to the parameter e just changes the value of the parameter, which isn't retained anywhere.
There's no need for Object.assign there, just create the object directly, so:
const replaced = album.songs.map(e => { return { _id : e }; } );
or the concise form:
const replaced = album.songs.map(e => ({ _id : e }) );
Note that since we want to return an object created with an object initializer, and the { in the initializer would start a function body, we wrap the value we want to return in ().
We can even take advantage of shorthand property notation if we change the name of the parameter to _id:
const replaced = album.songs.map(_id => ({ _id }) );
Live Example:
const album = {songs: [1234545, 43524]};
const replaced = album.songs.map(_id => ({ _id }) );
console.log(replaced);

You don't assign to the function parameter, since it only exists for that function, and it's not like you're dereferencing a pointer.
Just return the object. An arrow function automatically returns its expression if you don't use curly braces to denote the body.
var songs = [1234545, 43524];
const replaced = songs.map(e => ({_id: e}));
console.log(replaced);

Map function expects you to return a value for each iteration:
console.log([1, 2].map(n => n * 2))
In your case, it should be:
album.songs.map( e => ({ _id : e }))

Related

Vue JS - Using URLSearchParams is showing me error

I have an object and I need to pass it to the ajax request.
advanceSearch(e, field) {
this.searchString.push({
[field] : e
});
let q = new URLSearchParams(this.searchString).toString();
// this.searchTerm = e;
http.get('projects/search/'+q)
.then( ( response ) => {
console.log( response )
})
.catch( ( error ) => {
});
},
Here thissearchString is an array of object. I need to pass this array of object to the URL. So, I am using URLSearchParams but got this error message:
TypeError: Failed to construct 'URLSearchParams': The object must have a callable ##iterator property
I think you not understand the function of URLSearchParams.
Here, what this function do:
const paramsString = "myquery=value&topic=api"
const searchParams= new URLSearchParams(this.searchString)
// Convert the string into a URLSearchParams, this allow multiples methods on it.
With that you can apply multiple function, the common is to use it like that:
// const searchParams= new URLSearchParams(this.searchString)
for (let p of searchParams) {
console.log(p);
}
Output:
- ['myquery', 'value']
- ['topic', 'api']
Relative to https://developer.mozilla.org/fr/docs/Web/API/URLSearchParams
If i see your code, you want exactly the opposite of that.
You can easly do that like that:
const paramsString = {
myquery: 'value',
topic: 'api'
}
Object.entries(paramsString).map(params => `${params[0]}:${params[1]}`).join('&')
// Object entries define a value and a key. You map on that and got params[0] wich is a key and params[1] the value.
// In map you return a string and receive a array with ['key:value']
// You join all array to convert in a string and set a & between
output:
- 'myquery:value&topic:api'
With a array of object:
const paramsString = [{ id : 1 }, { brand : 'bata' }, { price : 123} ]
const result = paramsString
.map((params) =>
Object.entries(params).map(
(keyValue) => `${keyValue[0]}:${keyValue[1]}`
)
)
.join('&')
// You got each object on map
// Convert him to key & value like before and return a array with string
// Join each array with '&'

Get JSON value by using variables on the 2nd level of depth

I have a .json file like this:
{
"width": 700,
"height": 1382,
"dataID": {
"id1": "54321",
"id2": "12345"
}
}
I need to get value of id1 or id2 keys dynamically (using a variable). I use Cypress function cy.read() and by using definite strings it works good:
cy.readFile(pathToConfigFile).then(($file) => {
const id1value = $file.dataID.id1;
});
But how to wrap this expression into variable containing id1?
There is a similar question : Dynamically access object property using variable
However the solution proposed there refers only to the first level of depth. With square brackets I can get the following values:
cy.readFile(pathToConfigFile).then(($file) => {
const customVariable = "dataID";
const id1value = $file[customVariable];
});
But in case of it returns id1value = undefined:
cy.readFile(pathToConfigFile).then(($file) => {
const customVariable = "dataID";
const id1 = "id1";
const id1value = $file[customVariable][id1];
});
You will need to check the value of the variable after the first check so you know whether you can read the second-level value.
cy.readFile(pathToConfigFile).then(($file) => {
const customVariable = "dataID";
const id1 = "id1";
const idValues = $file[customVariable];
return idValues ? idValues[id1] : undefined;
});
Instead of undefined you can return some default value if you prefer.
There are also packages which can be used to do this automatically for you, such as lodash's _.get() method.

Modify object value in array inside map

Trying to modify object value in array on condition on some arrays the override does not work, here is my snippet
const removeAction = (target, array, name) => {
let mutation = JSON.parse(JSON.stringify(array));
mutation.map( obj => {
if(obj.value === target.value) {
console.log(obj)
obj.checked = false
}
return obj
})
console.log(mutation)
removeCallback(mutation, name)
}
and I get back the original object in array. How do I debug this issue?
const modifiedArray = JSON.parse(JSON.stringify(array)).map(...
Map always returns new instance of array. So either assign that mutated map to some variable or loop over and mutate the original array.
You could take the mapped objects with destructuring the object and an updated property.
const
removeAction = (target, array, name) => {
removeCallback(array.map(obj => ({
...obj,
checked: obj.value === target.value ? false : obj.checked
})), name)
};

What do parenthesis surrounding brackets in the return statement of an ES6 arrow function do?

For example in redux actions, I've seen in someone's code:
export const updateMessage = text => {
return (dispatch) => {
dispatch(updateChatMessage(text))
}
}
and:
const updateChatMessage = text => ({
type: types.someActionType,
text
})
it seems to function as an imply a return but I thought that was already implied in an arrow functions brackets following the fat arrow.
What do the parenthesis ({...}) do? are they necessary? Is there an alternate way to accomplish the same thing?
when you write myFunction = value => ({prop: value})
it return the object {prop: value}, in this case {} are object delimiter and not 'function delimiter'
const updateChatMessage = text => ({
type: types.someActionType,
text
})
another eg :
when you want to multiply by two each elem of an array you can write :
array.map(elem => {return elem * 2})
or
array.map(elem => elem * 2) //same result
and if you want an eg with () that wrap an object litteral :
let array = [{val: 2},
{val: 4},
{val: 8},
{val: 16}];
let output = array.map( ({val}) => ({val: val*2}) );
console.log(output);
If you wrap the brackets with parenthesis you are making your function return an object literal (thus you don't need the return keyword). If you don't use parenthesis you have to use the return keyword.
As per the arrow function docs,
// Parenthesize the body of a function to return an object literal expression:
params => ({foo: bar})
That means if you want to return an object implicitly you have to wrap it in parentheses.
Without this, code inside braces will be considered as function body and not an object (as you'd want)
Following are equivalent:
params => { return {foo: bar}} // Explicitly return an object (from function body)
params => ({foo: bar}) // Implicitly return an object by wrapping it with parentheses
In the first example, the {} are used to identify multiple lines of code, which is why the return is required in order to obtain something other than undefined.
In the second example, the {} are used to create an object.

Converting an array of objects in to a single object

Have an array which contains a no of json .
[{linkValue:"value1"},{linkValue:"value2"},{linkValue:"value3"},{linkValue:"value4"},{linkValue:"value5"}]
Note that each Json have same key . I want to convert this array into a single json like
{linkValue1:"value1",linkValue2:"value2",linkValue3:"value3",linkValue4:"value4",linkValue5:"value5"}
one thing i also need to know . my array is also inside a json how i get this arry from that json ?
My initial json is
{name:"value",age:"value",linkValue:[[{linkValue:"value1"},{linkValue:"value2"},{linkValue:"value3"},{linkValue:"value4"},{linkValue:"value5"}]
]}
I'm expcting my final json look like :
{name:"value",age:"value",linkValue1:"value1",linkValue2:"value2",linkValue3:"value3",linkValue4:"value4",linkValue5:"value5"}
can anyone please help me
Use Array.forEach and add properties to an empty object:
let source = {name:"value",age:"value",linkValue:[[{linkValue:"value1"},{linkValue:"value2"},{linkValue:"value3"},{linkValue:"value4"},{linkValue:"value5"}]]};
// Copy the array in a variable
let yourArray = source.linkValue[0];
// Delete the original array in the source object
delete source.linkValue;
yourArray.forEach((item, index) => {
source["linkValue" + (index + 1)] = item.linkValue
});
console.log(source); // Should have what you want
Using reduce API,
let targetObj = srcArr.reduce((accumulator, value, index)=>{
accumulator['linkValue'+(index+1)] = value.linkValue;
return accumulator;
}, {});
[{linkValue:"value1"},{linkValue:"value2"},{linkValue:"value3"},{linkValue:"value4"},{linkValue:"value5"}]
This is javascript Array contains multiple javascript object.
{linkValue1:"value1",linkValue2:"value2",linkValue3:"value3",linkValue4:"value4",linkValue5:"value5"}
If you need structure like this,Then define a single javascript object and add linkvalue1,linkvalue2 etc. as a member of that object and then add it to javascript Array.
Give this a try.
myObj.linkValue = myObj.linkValue.map((obj, index) => ({ [`linkValue${index + 1}`]: obj.linkValue }))
Solution with reduce
// HELPER FUNCTIONS
// pick properties from object with default value
function pick (props, sourceObj, defaultValue) {
return props.reduce(
(obj, prop) =>
Object.assign(obj, { [prop]: sourceObj[prop] || defaultValue }),
{}
)
}
// get property value or default
function propOr (propName, obj, defaultValue) {
return obj[propName] || defaultValue
}
// flatten nested array
function flattern (nestedArray) {
return nestedArray.reduce((flat, innerArray) => flat.concat(innerArray), [])
}
// LINKS BUILDER based on REDUCE
function buildLinks (linksArray) {
return linksArray.reduce((accumulator, item, index) => {
accumulator['linkValue' + (index + 1)] = item.linkValue
return accumulator
}, {})
}
// TRANSFORMATION FUNCTION - takes json and produce required output
function transform(json) {
return Object.assign(
{},
pick(['name', 'age'], json, null),
buildLinks(flattern(propOr('linkValue', json, [])))
)
}
// EXECUTION
const result = transform(source)
PS> You can use libraries like Lodash or Ramda and replace helper functions defined by me with ones from library

Categories

Resources