How to transform object into array? - arrays

I have an object which is dynamically built. I need to get some of the fields of this object (exactly the dynamic ones) and parse them into an array.
In the code below, I need to transform the towers[X] into an array of objects.
{id: "", description: "Teste", towers[1]: true, towers[2]: true,
towers[3]: true, …}
description: "Test"
id: ""
towers[1]: true
towers[2]: true
towers[3]: true
towers[4]: ""
}
I want it to be something like:
{
id: ""
description: "Test",
towers[1]: true //Don't care if it stays here or not, will not use
...
}
And a new array like:
{
[id: 1, value: true],
[id: 2, value: true],
[id: 3, value: true],
[id: 4, value: ""]
}

Just going to guess towers[0] gives back a number, if it does you can do this. This will find all keys that have boolean values and keep them and append them to a object.
const obj = YOUROBJHERE;
Object.keys(obj ).filter((key) => tyepof obj[key] === "boolean").reduce((accum, key) => {
return {...accum, [key]: obj[key]};
}, {})

in case of X=number and obj is the object we want to transform
let result = [];
for (let indx = 1; indx <=x ; i++) {
result.push({value:indx,value: obj['towers'+indx]})
}

If you want to transform your array of object you can do some like:
this.obj=this.obj.map(obj=>{
return {
id:obj.id,
description:obj.description,
towers:Object.keys(obj).filter((key) => key.indexOf('towers') != -1 )
.map((k,index)=>{
return {id:index+1,value:obj[k]}
})
.filter((x:any)=>x.value)
}
})
See that, map allow an "index" (begins by 0)

Related

Error: Response is not a function, when trying to find if the name exists

So I'm using mongodb to fetch some data from the database.
The issue is when I try to check for something in an array
Here is what the structure looks like:
Example array structure
{ // ...
likedPeople: [
{
name: "foo"
image: "test",
},
{
name: "bar",
image: "baz",
}
]
}
This is the array i get Back.
So when i try to find if it includes a certain value,
eg:
const displayName = "foo";
console.log(
likedPeople.map((likedPerson) => {
return likedPerson.name === displayName; // Output: [true, false]
})
);
But then If i again try to do some other method on it like map() or includes(), It breaks the setup:
const response = likedPerson.name === displayName; // Output: [true, false]
response.map((res) => console.log(res)); // Output: ERROR: response.map() is not a function
But the fact is that I am getting an array with the values, so what am I even doing wrong here?
I tried adding an optional chaining response?.map() but still it gave me the same error.
Also the includes() method also returns me the same response.includes is not a function error.
Can anyone help?
Use the some method to check the name exists in likedPeople :
const likedPeople = [
{
name: "foo",
image: "test",
},
{
name: "bar",
image: "baz",
}
];
const displayName = "foo";
const isExist = likedPeople.some(people => people.name === displayName);
console.log(isExist)

update one element of array inside object and return immutable state - redux [duplicate]

In React's this.state I have a property called formErrors containing the following dynamic array of objects.
[
{fieldName: 'title', valid: false},
{fieldName: 'description', valid: true},
{fieldName: 'cityId', valid: false},
{fieldName: 'hostDescription', valid: false},
]
Let's say I would need to update state's object having the fieldName cityId to the valid value of true.
What's the easiest or most common way to solve this?
I'm OK to use any of the libraries immutability-helper, immutable-js etc or ES6. I've tried and googled this for over 4 hours, and still cannot wrap my head around it. Would be extremely grateful for some help.
You can use map to iterate the data and check for the fieldName, if fieldName is cityId then you need to change the value and return a new object otherwise just return the same object.
Write it like this:
var data = [
{fieldName: 'title', valid: false},
{fieldName: 'description', valid: true},
{fieldName: 'cityId', valid: false},
{fieldName: 'hostDescription', valid: false},
]
var newData = data.map(el => {
if(el.fieldName == 'cityId')
return Object.assign({}, el, {valid:true})
return el
});
this.setState({ data: newData });
Here is a sample example - ES6
The left is the code, and the right is the output
Here is the code below
const data = [
{ fieldName: 'title', valid: false },
{ fieldName: 'description', valid: true },
{ fieldName: 'cityId', valid: false }, // old data
{ fieldName: 'hostDescription', valid: false },
]
const newData = data.map(obj => {
if(obj.fieldName === 'cityId') // check if fieldName equals to cityId
return {
...obj,
valid: true,
description: 'You can also add more values here' // Example of data extra fields
}
return obj
});
const result = { data: newData };
console.log(result);
this.setState({ data: newData });
Hope this helps,
Happy Coding!
How about immutability-helper? Works very well. You're looking for the $merge command I think.
#FellowStranger: I have one (and only one) section of my redux state that is an array of objects. I use the index in the reducer to update the correct entry:
case EMIT_DATA_TYPE_SELECT_CHANGE:
return state.map( (sigmap, index) => {
if ( index !== action.payload.index ) {
return sigmap;
} else {
return update(sigmap, {$merge: {
data_type: action.payload.value
}})
}
})
Frankly, this is kind of greasy, and I intend to change that part of my state object, but it does work... It doesn't sound like you're using redux but the tactic should be similar.
Instead of storing your values in an array, I strongly suggest using an object instead so you can easily specify which element you want to update. In the example below the key is the fieldName but it can be any unique identifier:
var fields = {
title: {
valid: false
},
description: {
valid: true
}
}
then you can use immutability-helper's update function:
var newFields = update(fields, {title: {valid: {$set: true}}})

add dynamic empty objects to an array React

I have the following code, which basically adds empty objects to an array.
handleAddNewRow = () => {
this.setState({
rowData: [
{ MEMBER: "", ALIAS: "", STATUS: "" },
...this.state.rowData
]
})
}
Lets say, I am passing an integer value to the function handleAddNewRow and then it dynamically adds the number of empty objects to the array based on the integer value, How is it possible?
You can look at my function:
handleAddNewRow = (number) => {
this.setState({
rowData: [
...this.state.rowData,
...(new Array(number).fill({ MEMBER: "", ALIAS: "", STATUS: "" }))
]
});
}
in the following code i wrote code in simple condition
change it on your own
const array = [{name: '', family: ''}]
function a(num, arr) {
let temp = [...arr, {name: '', family: ''}]
if (num - 1 > 0) {
temp = a(num - 1, temp)
}
return temp
}
const b = a(4, array)
console.log(b)

search the element in array using angular 4

I have array list of items like the below
let sourceList: SourceList[] = [
{
Value: "L7",
Name: "L7",
IsVisible: false
},
{
Value: "LO",
Name: "LO",
IsVisible: false
},
{
Value: "L3",
Name: "L3",
IsVisible: false
},
{
Value: "LS",
Name: "LS",
IsVisible: false
}
]
code tried so far
if(this.sourceList.indexOf("L7",0) != -1 && this.selectedSources.indexOf("LO",0) != -1 ){
}
but getting an error at "L7"
I am adding items from this souceList array to another array say array2 one by one ..
is there any way to check whether the item from the souceList array is in array2 or not ..
I need to do some process if item "L7" and "LO" is in array 2
but I am not able to figure out how can i search both the items at a time in array 2 ..
I am using angular 4 ..
Could any one please help on this, that would be very grateful to me
You can use the some method:
if (this.sourceList.some(x => x.Value === "L7") &&
this.selectedSources.some(x => x.Value === "L0")) {
...
}

transform json object to an array field

I want to transform a list of objects with object having this form
{
"idActivite": 1,
"nomActivite": "Accueil des participants autour d’un café viennoiseries",
"descriptionActivite": "",
"lieuActivite": "",
"typeActivite": "",
"horaireDebActivite": 1512028800,
"horaireFinActivite": 1512059388,
"horaireDebSession": 1512030600,
"horaireFinSession": 1512318588,
"nomSession": "",
"isInSession": false
}
to a one like this :
[
"idActivite": 1,
"nomActivite": "Accueil des participants autour d’un café viennoiseries",
"descriptionActivite": "",
"lieuActivite": "",
"typeActivite": "",
"horaireDebActivite": 1512028800,
"horaireFinActivite": 1512059388,
"horaireDebSession": 1512030600,
"horaireFinSession": 1512318588,
"nomSession": "",
"isInSession": false
]
using type script 2.5
Both are theoretically still objects and that isnt the right way to go about it! An array is simply a list of elements with a number index, the example you are giving uses a string to index and thus is still according to the JSON spec an object. If the issue you are having is to iterate through it use this:
for(var key in array){
console.log(array[key]);
}
Assuming you want an array like [ {key, value} ]
let x = { a: 1, b: 2 }
let y = []
// Note the 'in' keyword instead of 'of'
for (const key in x) {
y.push({ key: key, value: x[key] })
}
// Will print [ { key: 'a', value: 1 }, { key: 'b', value: 2 } ]
console.log(y)
Note that this solution scales linearly with the size of the array.

Resources