How to push array value with defined object in angular - arrays

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

Related

trying to push two specific values into another array as a key value pair using typescript

Newbie here and this is a project I'm building to learn. I'm going around in circles so forgive my ignorance please. I'm now not even sure that what I want to do is possible. I also understand that there are probably better ways to achieve my ultimate goal but this is what I have.
I have an array that includes some user input.
"participants": [ {
"name": "Cristina",
"email": "cristina#gmail",
"yourPerson": "Richard",
"spouseEmail": "Richard#gmail" } ] }
I want to pull the "name" and "youPerson" values and use them as a key:value pair. So name would be the key and yourPerson would be the value.
I thought I could use a forEach but no matter what I do I either get an undefined array or I copy the entire array, not just those two fields.
here is my code at the moment:
participantArray = [];
namePlusSpouseArray = [];
submitParticipant() {
this.participantArray.push(this.participantForm.value);
console.log(this.participantArray)
this.createNamePlusSpouseArray();
}
createNamePlusSpouseArray() {
this.participantArray.forEach(name => {
this.namePlusSpouseArray.push(this.participantArray[name]);
console.log(this.namePlusSpouseArray)
});
}
Not sure if you want a result array of key value pairs, or you want 1 object/map/dictionary/lookup of name -> youPerson
Assuming you want an array containing key value pairs, you can use map
this.namePlusSpouseArray = this.participantArray.map(participant => ({
[participant.name]: participant.youPerson
});
If you want a lookup of name -> youPerson, the "namePlusSpouseArray" shouldn´t be an array but instead just an object
namePlusSpouseLookup = {};
this.participantArray.forEach(participant => {
this.namePlusSpouseLookup[participant.name] = participant.youPerson;
});
The simplest solution is:
const participantArray = {
"participants": [ { "name": "Cristina", "email": "cristina#gmail", "yourPerson": "Richard", "spouseEmail": "Richard#gmail" } ] };
const createPair = participants => {
return participants.map(participant =>
({ [participant.name]: participant.yourPerson}))
}
console.log(createPair(participantArray.participants));

How can I use .map on an array to create a new JSON object for each item?

how can I use map on an array to map each item to a new JSON structure?
For example my original array looks like this:
result= [
{
"pageIndex":1,
"pageName":"home",
"cssConfiguration":"fa fa-home"
}, ...]
And I want to use .map to create a different structure for the JSON objects, for example:
modifiedResult = [
{
"id":1,
"name":"Home"
},...]
I've tried to do something like this:
result.map((resultItem) => { name: resultItem["pageName"], id:resultItem["pageIndex"]});
But it doesn't work :(
In your approach are missing the parentheses within the handler:
result.map((resultItem) => { name: resultItem["pageName"], id:resultItem["pageIndex"]});
^
You can use the function map and destructuring-assignment as follow:
let arr = [ { "pageIndex":1, "pageName":"home", "cssConfiguration":"fa fa-home" }],
result = arr.map(({pageIndex: id, pageName: name}) => ({id, name}));
console.log(result)
You can use map:
const result = arr.map(({pageIndex, pageName}) => ({id: pageIndex, name: pageName}))
An example:
let arr = [
{
"pageIndex":1,
"pageName":"home",
"cssConfiguration":"fa fa-home"
}]
const result = arr.map(({pageIndex, pageName}) => ({id: pageIndex, name: pageName}))
console.log(result)

Simple reducer accumulator should not be mutating the state, why is it?

For some reason my reducer is only returning a single element in the categories collection.
I'm just learning this accumlator logic, so I have kept it simple which I thought was suppose to simply return the exact same state as I started with.
My state in JSON looks like:
{
"account":{
"id":7,
"categories":[
{
"id":7,
"products":[
{
"productId":54
}
]
},
{
"id":9,
"products":[
{
"productId":89
}
]
}
]
}
}
In my reducer I have the following:
return {
...state,
account: {
...state.account,
categories: [state.account.categories.reduce((acc, cat) => {
return {...acc, ...cat}
}, {})]
}
};
When I output my state, I see that for some reason it has removed one of the categories from the collection.
Why isn't my state the same since the accumulator isn't filtering anything? It should be the exact same as it started with.
if you want to return categories unchanged (but with a different reference), you should do it like this:
categories: state.account.categories.reduce((acc, cat) => {
return [...acc, cat];
}, [])
In your code accumulator value is an object with categories props that is constantly overwritten by another item from an array so in the end only the last item is present.
Let's put aside react and redux and focus on reduce function. It takes an array and returns something different using the function called a reducer.
In the following example:
const array = [{num: 1}, {num: 2}];
you can take each of the elements of an array and merge their properties:
array.reduce((acc, item) => ({...acc, ...item}), {})
this is equal to
Object.assign({}, array[0], array[1]);
or
{...array[0], ...array[1]}
and result is {num: 2}, (first there was an empty object {}, then {num: 1} and finally {...{num: 1}, ...{num: 2}} gave {num: 2}
It doesn't matter if you enclose it in an array, it's still a one object created from merging all objects in the array together
If you want a copy of an array. This can be done like this:
array.reduce((acc, item) => [...acc, item], []);
This is equal to
[].concat(...array);

Reading JSON into arrays in Angular (HttpClient)

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}
})
})

How to list a property of firebase object as an array?

I have a firebase databse with the following structure:
Each one of those random UIDs have creator and roomName. I am trying to display all roomName in an array, like ["Holy Robert Louis Stevenson", "Holy Sardine", "Holy Gunpowder"], but it is always displayed as [Object, Object, Object]
Here is my code:
const dbRef = firebase.initializeApp(config).database().ref().child('rooms');
...
componentDidMount(){
dbRef.on('value', snap => {
console.log(snap.val());
console.log('firebaseHolyArray: ', Object.values(snap.val()));
});
}
I hav tried console.log('firebaseHolyArray: ', Object.values(snap.val())["roomName"]); but it displays undefined. How can I display the values of roomName in array format?
You can use the forEach() method, which will produce a properly ordered list from Firebase data:
dbRef.on('value', snap => {
var data = [];
snap.forEach(ss => {
data.push(ss.child('name').val());
});
console.log(data);
});
There's no need to do multiple iterations with Object.values() or using underscore, both of which will likely produce out of order data and other complications here.
Also, ideally you should get into the habit of using the recommended practices for working with lists, such as child_added.
I think snap.val() is returning something like this:
{
"-KeoiS8luCsuKhzc_Eut": { "creator": "Robin", "roomName": "Holy Robert Louis Stevenson" },
"-Keol-2Si05dmkmuac8l": { "creator": "Robin", "roomName": "Holy Sardine" },
"-KeooOxSoYNdNk6g5DMw": { "creator": "Robin", "roomName": "Holy Gunpowder" }
}
We can use Object.values(snap.val()) to transform it into an array of objects, like this:
[
{ "creator": "Robin", "roomName": "Holy Robert Louis Stevenson" },
{ "creator": "Robin", "roomName": "Holy Sardine" },
{ "creator": "Robin", "roomName": "Holy Gunpowder" }
]
Then, we want to extract the room name from each object. The array map method would be helpful in this situation to transform the objects into what we want. In the end, I think it should look something like this:
var rooms = Object.values(snap.val()).map(function(obj) {
return obj.roomName;
});
console.log('firebaseHolyArray: ', rooms);
This will take the array of objects, and pass each one into our function. In that function, you can return what part of the object you want to end up with...In this case, the roomName. You will be left with an array of these, which you can easily print out.
Object.values() returns Object[].
So, it doesn't cotain "roomName" attribute.
I think you use map for pluck.
Here is code
console.log('firebaseHolyArray: ', Object.values(snap.val()).map((v) => v.roomName);
If you use underscore, you can also use underscore.pluck.
console.log('firebaseHolyArray: ', _.pluck(Object.values(snap.val()), "roomName"));
Refer to http://underscorejs.org/#pluck
export const mapObjectToArray = (obj: any) => {
const mappedDatas = [];
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
mappedDatas.push({ ...obj[key], id: key });
}
}
return mappedDatas;
};
Here a function that I use to convert a Firebase object in an array.
let data = [];
const keys=Object.keys(rooms);
const values=Object.values(rooms);
for (let i = 0; i < keys.length; i++) {
const temp={
key:keys[i],...values[i];
}
data.push(temp);
}

Resources