I am getting a JSON object from Firebase. I am trying to convert it into an array of objects.
I can solve this by getting childs from Firebase one-by-one and add them into array however, that is not a good practice for my case.
The format of JSON object is as following:
key: {
id1: {some stuff here},
id2: {some other stuff},
...
}
Now what I want to get from this JSON object is :
arrayName: [
{id1:{some stuff here},
id2:{some other stuff}
]
Hope my description if fully understandable.
Any help would be appreciated
This is just plain javascript, it has nothing to do with react native. By the way, you can use Object.keys to get an array with all the keys, then map the strings as objects:
const x = {foo: 11, bar: 42};
const result = Object.keys(x).map(key => ({[key]: x[key]}));
console.log(result);
This code worked for me.
const JSONString = res.data;
object = JSON.parse(JSONString);
array = Object.keys(object).map(function(k) {
return object[k];
});
Where res.data is the response I am getting from an api
Using Object.entries, you can avoid the extra hash lookup on every item.
const x = { foo: 11, bar: 42 };
const result = Object.entries(x).map(([key, val]) => ({
[key]: val
}));
console.log(result);
Related
in firestore I have a document with two strings and also an object array with [{email: ..., id: ..., nickname: ...} {...}]
I use a subscription to get all users from that specific document. The next step is to extract all ids from that object array (called "users") in a new array.. But I have no idea how to do this.
I try somethink like this:
this.group.forEach(element => console.log(element)
"this.group" is the subscription of that document. But this output display all content from this document and not the only array called (users)See attachement.
Hope anyone can help?
You can loop it and push it in a new array like this. See sample code below:
const docSnap = await getDoc(docRef);
const newArray = [];
if (docSnap.exists()) {
const users = docSnap.data().users
users.forEach(element => {
newArray.push(element.id);
})
// This will return an array of `id` from the `users` array.
console.log(newArray);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
The same logic will be applied if you use it to the subscription of the document.
I'm attempting to sort an array of maps by a particular key/value within the maps.
Map<string, string>[]
I get back the following error,
Cannot assign to read only property '0' of object '[object Array]''
I'm trying to make heads or tails of this error but I feel like I'm not returning the correct value somewhere. I think my code looks mostly correct. I'm more concerned I may be trying to do something that is more difficult than I realize. Here is my code. I hard-coded the key for now just try and work through the problem and that key does exists. Any insight would be great. Thanks for looking.
sortGridData(data$ : Observable<Map<string, string>[]>) : Observable<Map<string, string>[]> {
const sortedData$ = combineLatest([data$, this.sort$]).pipe(
map(([data, sort]: [Map<string, string>[], SortDescriptor[]]) => {
data.sort((item1, item2) => {
return this.compareObjects(item1, item2, 'version')
})
return data;
})
);
return sortedData$;
}
compareObjects(object1 : Map<string, string>, object2: Map<string, string>, key) {
let item1 = object1.get(key);
let item2 = object2.get(key);
const obj1 = item1.toUpperCase()
const obj2 = item2.toUpperCase()
if (obj1 < obj2) {
return -1
}
if (obj1 > obj2) {
return 1
}
return 0
}
Sort Grid data is called at another point in my component. I'm not sure that is entirely relevant.
I will assume that the data is coming from some state-management observable based library.
If my assumption is correct the issue is because you try to mutate immutable element, what i mean is that Array.sort is making changes over the existing array named data, a.k.a. it mutates it, and because the data itself is an immutable array (read-only no modification allowed) you are receiving this error.
The thing that will most-likely solve your issue is to create a copy of the data array, and after that sort the elements inside this new copy.
sortGridData(data$ : Observable<Map<string, string>[]>) : Observable<Map<string, string>[]> {
const sortedData$ = combineLatest([data$, this.sort$]).pipe(
map(([data, sort]: [Map<string, string>[], SortDescriptor[]]) => {
// here we create a new array, that can be mutated
const dataCopy = [...data];
dataCopy.sort((item1, item2) => {
return this.compareObjects(item1, item2, 'version')
})
return dataCopy;
})
);
return sortedData$;
}
If this doesn't solve your issue please provide some more context about from where is the sortGridData being called, and to what is the data$ referring to, when the function is called.
My array
let myArr=["test1","test2"];
Need to add the object like below
let myFinalArr=[["test1":{"val1":"XXX","val2":"YYY"}],["test2":{"val1":"XXX","val2":"YYY"}]];
how to push the data like above in angular.
There are multiple ways to do it. How exactly does the requirement look? Does the object remain same for all the elements in the array?
And expanding from your comment that the following is the actual output's structure
{
"test1": { "val1":"XXX", "val2":"YYY" },
"test2": { "val1":"XXX", "val2":"YYY" }
}
You could try the Array#reduce with spread operator to transform the array
let myArr = ["test1", "test2"];
const output = myArr.reduce((acc, curr) => ({
...acc,
[curr]: { val1: "XXX", val2: "YYY" }
}), Object.create(null));
console.log(output);
i am trying to read JSON into different arrays using HttpClient for the use in Echarts, but since i am a newbie i couldn't find how to fill JSON into the different arrays.
the part code i used so far was:
....
label: Array<any>;
data: Array<any>;
tooltip: Array<any>;
constructor(private http: HttpClient) {
this.getJSON().subscribe(data => {
this.data=data.data;
this.label=data.label;
this.tooltip=data.tooltip;
console.log(data)
});
}
public getJSON(): Observable<any> {
return this.http.get("./assets/JSONData/TeamProgress.json")
}
the JSON file is formatted like this:
[{"label":"0","data":"0","tooltip":"0"},
{"label":"1","data":"-1","tooltip":" tooltip1"},
{"label":"2","data":"-1","tooltip":" tooltip2"},
...etc
i want to be able to get all labels of JSON in one array, and all data in another array, and all tooltips in a third array.
it would be great if you can help me.
thanks
First the result of that file should be a valid JSON structure aka (an object with key-values) you can group the array under a key called per example result
{
"result": [
{"label":"0","data":"0","tooltip":"0"},
{"label":"1","data":"-1","tooltip":" tooltip1"},
{"label":"2","data":"-1","tooltip":" tooltip2"},
//....Etc
]
}
Then you can access the data and filter it using map as below:
this.getJSON().subscribe((data:any) => {
this.label = data.result.map(element =>
// if you want to return an array of objects
{return {"label": element.label}}
// or if you want to return the raw values in an array, just do
element.label
});
this.data = data.result.map(element => {
return {"data": element.data}
});
this.tooltip = data.result.map(element => {
return {"tooltip": element.tooltip}
})
})
I have the follow object:
formData : {
_id: "550de8956e2d0948080e220f"
category: "Tag1"
isFeatured: "Yes"
likeCount: 557
title: "Integrating WordPress with Your Website"
}
I tried JavaScript but it returned a null value:
var arryFormData = Array.prototype.slice.call(formData)
How can I convert formData into an array of just its values, not properties?
As in ...
arryFormData = ["550de8956e2d0948080e220f", "Tag1", "Yes", 557, "Integrating WordPress with Your Website"]
or if You like to more functional code:
var arr = [];
angular.forEach(obj, function(value, key){
arr.push(value);
});
If you are using underscore.js,
_.values(formData)
// will get ["550de8956e2d0948080e220f", "Tag1", "Yes", 557, "Integrating WordPress with Your Website"]
See: here
Alternatively:
var res = [];
for (var x in formData){
formData.hasOwnProperty(x) && res.push(formData[x])
}
console.log(res);
In any event, the array elements might not be in the order that you want.
I prefer one line solution with Object.keys() and es6 syntax, until Object.values() is not here
const values = Object.keys(obj).map(it => obj[it])
or in es5
var values = Object.keys(obj).map(function(it) {
return obj[it]
})
I think there's No magic way, you just have to use a for loop:
for (var key in obj) {
values.push(obj[key])
}
To make it angular, you could use angular.forEach I guess...
This is how i have handled in Angular 5 to convert Object into Array as API gives response in JSON Object so we can convert it into array to use it.
let tmepArr = {};
Object.keys(res).forEach( key => {
tmepArr['name'] = [res[key].name];
tmepArr['id'] = [res[key].id];
});
this.marketplaceDropDown = [tmepArr];