Getting multiple values from JSON - javascript

I'm attempting to pull multiple values to create a list in the form of a string. When I am pulling my data it responds as such.
data = [{name: 'value'}, {name: 'value'}, {name: 'value'}]
I need the end product to be "value, value, value" although I'm unsure at the moment on how to go about this.

Let's use Array#Map in JavaScript.
You can see how to use it on MDN here
var data = [{name: 'value'}, {name: 'value'}, {name: 'value'}]
var result = data.map(a => a.name);
console.log(result)

const arr = data.map(elem => elem.value)
In your case, the data object is an array.
You can use the map function, that will iterate over the array elements, it returns a new array with values from the map function callback

Related

On submit send data to API by taking data from an array of objects in react

On submit I want to call a function and send data as object of key value , taking data from an array of objects
const [documents,setDocuments] = useState({});
let selected= [
{name: 'Profile', value:'S'},
{name: 'Pan card', value:'P'},
{name: 'Document(Investment proof) ', value:'IP'}
]
function onSubmit(){
selected.map(data=>setDocuments({...documents, [data.value]: data.value}))
axios.post(`api`, documents)
}
result should be like this: axios.post(api, {S:'S', P:'P', IP:'IP'})
useState and setState both are asynchronous. if you send object use reduce.
const obj = selected.reduce((pre,curr)=>{
pre[curr.value] = curr.value
return pre
},{})
axios.post(`api`, obj)

Mutating/Updaing array of objects while destructuring object properties not mutating the array

I have recently discovered an interesting behavior while mapping my array of objects and using destructuring og the object properties
var arr = [
{name: 'John'},
{name: 'Peter'},
]
arr.map(({name}) => {
name = 'Lars'
return name;
})
console.log(arr) //prints [{name: 'Johh'}, {name: 'Peter'}]
Seems like the destructured properties are only re-assigned to the object, but the object is not re-assigned to the array.
If I drop using destructured values in my map function it and keep object reference it is going to work.
arr.map((item) => {
item.name = 'Lars'
})
console.log(arr) //prints [{name: 'Lars'}, {name: 'Lars'}]
Is there any way to mutate the array while using destructured properties in a map or a similar function ?

Javascript: map function appending to an object

I have a map function which is iterating a response i received from backend. I'm iterating the response as 'tab' like the code below, what i want to do is to insert 'tab.name' as an key inside the object MyObject
my code:
var MyObject = {}
response.data.rows.map(tab => {
MyObject = {
...MyObject,
tab.name
}
})
What i expect is that my object MyObject has every keys and values with the name of tab, e.g:
{
name1: name1,
name2: name2,
name3: name3
}
The problem is that i can not use tab.name inside object
You could use collectjs, goes good..
Anyway if you want to have the keys just do a foreach
let response = [
{name: 'name1', age: '22'},
{name: 'name2', age: '25'},
{name: 'name3', age: '2'},
]
var MyObject = {}
response.forEach(tab => {
MyObject[tab.name] = tab.name
})
console.log(MyObject)
If you really want to use .map(), you could use to create an array of arrays, where each sub-array has a length of 2, and holds the given value at each index.
Then you can use Object.fromEntries() to add the properties from that array structure.
var response = {data:{rows:[{name:"foo"}, {name:"bar"}, {name:"baz"}]}};
var key_val_props = response.data.rows.map(({name}) => [name, name]);
var MyObject = Object.fromEntries(key_val_props);
console.log(MyObject);
Theres no need to copy the object just do
MyObject[tab.name] = tab.name;
I'd also avoid using .map since it will be returning the new reference which I dont think that is what you want.

Converting an array of objects to Map Immutable.js

I have an array of objects which I wish to convert into a plain Immutable map of:
name: {
urlname
id
}
Currently I am doing the following data being the array of objects:
data = data.map((data) => ({
name: data.name,
urlName: data.urlName,
id: data.id
}))
What I am trying to transform is the following (data):
[{"id":"10","name":"Dave","urlName":"foo-bar","order":"-100","classId":"12","className":"David","classUrlName":"david-foo-bar"}]
As said above, I would like the name as the key, and both the urlName and the id as values to the key if possible. I would like to loop around data until everything is reduced to that structure if possible.
Since you want to transform the data from shape to shape, you can use the reduce function to do this job.
the reduce function will transform the data into a Map where each key is a name, and the values are the id and urlName
const sample = [{"id":"10","name":"Dave","urlName":"foo-bar","order":"-100","classId":"12","className":"David","classUrlName":"david-foo-bar"}];
const result = sample.reduce((acc, item) => {
return acc.set(item.name, {
id: item.id,
urlName: item.urlName,
})
}, new Immutable.Map())
console.log("Dave's Id", result.getIn(["Dave", "id"]));
console.log("Date's urlName", result.getIn(["Dave", "urlName"]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.9/immutable.js"></script>
Check the documentation here for ImmutableJS Reduce and Native Javascript Array.reduce. Both are identical in their API.

Retrieve only one field from object/array using underscore.js

In ruby I'm able to do the following:
myObject.map(&:name)
And I get an array composed by all the name field for all values inside myObject (array or object).
What's the underscore.js or lodash.js equivalent? I prefer in only one line if possible :)
Example: (in js)
_.map([{name: 'x'}, {name: 'y'}], function(obj){
//dosomething
})
_.pluck([{name: 'x'}, {name: 'y'}],"name");
this will give you: ["x","y"];
see http://underscorejs.org/#pluck
For lodash users,
_.map([{'name': 'x'}, {'name': 'y'}], 'name');
// ['x', 'y']
Using pure Javascript simply use map
let data = [{name: 'x'}, {name: 'y'}];
data.map( (item) => item.name );
Will return you ["x", "y"].

Categories

Resources