I have a project where I have to take some data from a GoogleSheet document and send it to database.
I get the data from googlesheet document, but the problem is how is the data structured.
[
{
class: "A",
name: "Alex",
age: 13
},
{
class: "A",
name: "Mary",
age: 14
},
{
class: "B",
name: "John",
age: 13
},
{
class: "B",
name: "William",
age: 12
}
]
The problem is I want my JSON object to look like this
[
"A": {
{
name: "Alex",
age: 13
},
{
name: "Mary",
age: 13
}
},
"B": {
{
name: "John",
age: 13
},
{
name: "William",
age: 13
}
}
]
Any idea how can I do that? I want to group my objects over an element, like the class. All the people with the same class value to be in the same group/json.
You can make use of Array.reduce and format it.
let data = [{class:"A",name:"Alex",age:13},{class:"A",name:"Mary",age:14},{class:"B",name:"John",age:13},{class:"B",name:"William",age:12}];
//destructuring and renaming it to `_` as `class` is a pre-defined identifier in javascript
const formatData = (data) => data.reduce((res, {
class: _,
...rest
}) => {
//(res[_] || []) --> If the `class` prop is not already present in the res object, then using empty array
//If already present spreading res[_] and adding the current object to the existing array
res[_] = [...(res[_] || []), { ...rest }]
return res;
}, {})
console.log(formatData(data))
.as-console-wrapper {
max-height: 100% !important;
}
You can have a look at Destructuring Assignment for more info about destructuring and assigning new variable names.
Related
What I want to achieve is to add each key value of array b to each object in array a, but not to merge them as I've tried that already and it's no something that it helps, I basically want to add the key and value that I don't have in array a from array b.
array a = [
{
name: "Alex"
},
{
name: "Helen"
},
{
name: "Anna"
}]
array b = [
{
age: "23"
},
{
age: "24"
},
{
age: "25"
}]
What I want to achieve is:
array a = [
{
name: "Alex",
age: "23"
},
{
name: "Helen",
age: "24"
},
{
name: "Anna",
age: "25"
}]
I've tried the options available in here but nothing seems to work. If you guys have any idea, I would really appreciate it.
Use Array.prototype.map():
const a = [{name:"Alex"},{name:"Helen"},{name:"Anna"}],
b = [{age:"23"},{age:"24"},{age:"25"}],
result = a.map(({name},i) => ({name, ...b[i]}))
console.log(result)
.as-console-wrapper{min-height:100%;}
I have this object inside a json:
{
"group": "A",
"id": "50"
"person": [
{
"name": 'Joe',
"age": '29'
"hobbies": ["Watching movies", "Gaming"]
},
{
"name": 'Jessie',
"age": '27'
"hobbies": ["Gaming", "Reading"]
}
]
}
I want to filter the people by their hobbies. For example, if I filter by Gaming I need to create an array of objects with Joe and Jessie. If I filter by Reading, then the array would only have Jessie.
Here is my code:
import { people } from '../../../data/index' // this is the json I shower above
let filteredArray;
filteredArray = people.filter(person => {
return person.hobbies == "Gaming";
})
this doesn't work, but if change the hobbies to a single word on the json, like this:
{
"name": 'Jessie',
"age": '27'
"hobbies": "Gaming"
}
then it work just fine.
So is there a way to use filter with a array of hobbies to check if one of the values match my condition?
I'm using only vanilla Js and I only want to support chrome.
Sorry for any english mistake or if the question is not clear enought, I'm still in the beggining of my studies
You have to use includes method. Because you are trying to search in array:
const filteredArray = people.filter(person => {
return person.hobbies.includes("Gaming");
})
const data = {
group: 'A',
id: '50',
person: [
{
name: 'Joe',
age: '29',
hobbies: ['Watching movies', 'Gaming']
},
{
name: 'Jessie',
age: '27',
hobbies: ['Gaming', 'Reading']
}
]
};
const result = data.person.filter(el => el.hobbies.includes('Gaming'));
console.log(result);
This question already has answers here:
How to set specific property value of all objects in a javascript object array (lodash)
(3 answers)
Closed 4 years ago.
I am declaring an empty array of objects called filter in constructor:
constructor(props){
super(props);
this.state = {
filter: []
}
}
I am getting an API response which is an array objects something like below and storing in filter variable.
[
{
name: "xyz",
language: "english",
age: 20
},
{
name: "abc",
language: "history",
age: 21
},
{
name: "efi",
language: "geography",
age: 20
}
]
I was looking for a way where I can set a property like checked = false for each object in filter array by default in jsx file. Though the response from API is above, after receiving the response, the array should like
[
{
name: "xyz",
language: "english",
age: 20,
**checked: false**
},
{
name: "abc",
language: "history",
age: 21,
**checked: false**
},
{
name: "efi",
language: "geography",
age: 20,
**checked: false**
}
]
using map and Object.assign, assuming obj is the respanse that you get from your api you can run the function below to parse your array an then set the respanse to your state
var obj=[
{
name: "xyz",
language: "english",
age: 20
},
{
name: "abc",
language: "history",
age: 21
},
{
name: "efi",
language: "geography",
age: 20
}
]
var result = obj.map(el => {
var o = Object.assign({}, el);
o.checked = false;
return o;
})
console.log(result);
Api.post(JSON.stringify(ConditionJson), AppConst.BaseURL + 'query/execute/conditions/LoyaltyStamps', (err, responseJson) => {
if (err) {
Alert.alert('Error!', err);
}
else {
var checked = 'false';
var name = responseJson.map(function (info) {
checked += 'false';
});
this.setState({
ischecked: checked
});
}
Cant seem to find any threads that talk about this type of data structure manipulation.
I have a new API schema for a service that I am replacing. The original API returned an array of objects.
[
{name: 'Conner', age: 24, gender: 'male'},
{name: 'Bryan', age: 32, gender: 'male'}
]
The new response looks like..
{
fields: {
name: {
values: [
'Conner',
'Bryan'
]
},
age: {
values: [
24,
32
]
},
gender: {
values: [
'male',
'male'
]
}
}
}
What would be the best/most minimal way to transform the response to the existing format: an array of objects. I can use vanilla javascript or Lodash.
I've made it tick like you want it to by taking the length of the values of the name prop, in order to determine how many iterations/people we have.
Still, this is a very peculiar data set - but here goes:
const fields = {
name: {
values: [
'Conner',
'Bryan'
]
},
age: {
values: [
24,
32
]
},
gender: {
values: [
'male',
'male'
]
}
}
const previous = fields.name.values.map((item, i) => {
return Object.keys(fields).reduce((obj, key) => {
obj[key] = fields[key].values[i]
return obj
}, {})
})
console.log(previous)
First array
userData = [
{ name: abc, age: 24 },
{ name: ghi, age: 22 },
{ name: tyu, age: 20 }
];
Second array
userAge = [
{ age: 25 },
{ age: 26 },
{ age: 22 }
];
Both arrays have the same length.
How do I update the useData[0].age with userAge[0] using Underscore.js?
Since you need to do this over a list of dictionaries, you will need to iterate over the list using _.each.
Something like this will help,
_.each(userData, function(data, index) {
data.age = userAge[index].age;
});
While #martianwars is correct, it could be a little more generic, thus more useful, if it could apply any attribute.
Say we have an array of changes to apply, with each not being necessarily the same attribute or even multiple attributes per object:
var changes = [
{ age: 25 },
{ name: "Guy" },
{ name: "Pierre", age: 22 }
];
Changes could be applied with _.extendOwn
_.each(userData, function(data, index) {
_.extendOwn(data, changes[index]);
});
Proof of concept:
var userData = [{
name: "abc",
age: 24
}, {
name: "ghi",
age: 22
}, {
name: "tyu",
age: 20
}];
var changes = [{
age: 25
}, {
name: "Guy"
}, {
name: "Pierre",
age: 22
}];
_.each(userData, function(data, index) {
_.extendOwn(data, changes[index]);
});
console.log(userData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
This will only work if the arrays are in sync. Meaning that if there are 4 objects in the userData array, and only 3 changes, they need to be at the right index and that could become a problem.
A solution to this is to have an identification property, often represented by an id attribute.
userData = [
{ id: '1', name: 'abc', age: 24 },
{ id: '2', name: 'ghi', age: 22 },
{ id: '3', name: 'tyu', age: 20 }
];
See Merge 2 objects based on 1 field using Underscore.js for details.