Declaring a javascript array of infinite objects - javascript

How can I declare a JavaScript object which can hold infinite amount of values like given below? I am new to Javascript.
var activities = [
{
subject: "",
genre :"",
username: "",
aboutuser: ""
},
{
subject: "",
genre :"",
username: "",
aboutuser: ""
},
{
subject: "",
genre :"",
username: "",
aboutuser: ""
},
...
]

Like this:
let myArray = []
myArray.push({
subject: "",
genre :"",
username: "",
aboutuser: ""
})
Just define an empty array and push the object into it as many times you need.

Related

merging objects delete initial keys

I have two objects obj1 & obj2.
when I merge with:
const obj1 = {
error_to_retrieve: "teste",
error_to_search_customer: "",
error_to_sync_timezone: "",
error_to_update_avatar: "",
error_to_update_profile: "",
error_to_validate_customer_token: "",
expired_session: "",
invalid_token: "",
invalid_token_text: ""
}
const obj2 = {
error_to_retrieve: "test",
error_to_search_customer: "test",
error_to_sync_timezone: "test",
error_to_update_avatar: "test",
error_to_validate_customer_token: "test",
expired_session: "test",
invalid_token: "test",
invalid_token_text: "test"
}
const obj3 = {...obj1, ...obj2};
console.log(obj3);
I get the full obj2, and it dont have the key error_to_update_profile.
How I maintain the key of the first object that my second dont have?
Use Object.prototype.hasOwnProperty() to check whether your final objects has the property key error_to_update_profile. The funtion returns true which is prove that the merge worked perfectly fine as intended.
const obj1 = {
error_to_retrieve: "teste",
error_to_search_customer: "",
error_to_sync_timezone: "",
error_to_update_avatar: "",
error_to_update_profile: "",
error_to_validate_customer_token: "",
expired_session: "",
invalid_token: "",
invalid_token_text: ""
};
const obj2 = {
error_to_retrieve: "test",
error_to_search_customer: "test",
error_to_sync_timezone: "test",
error_to_update_avatar: "test",
error_to_validate_customer_token: "test",
expired_session: "test",
invalid_token: "test",
invalid_token_text: "test"
};
const obj3 = { ...obj1, ...obj2 };
console.log(obj3.hasOwnProperty("error_to_update_profile"));
You can change the order of what to write, i.e. whatever you put last will overwrite all previous entries { ...obj2, ...obj1 } → obj1 will overwrite obj2 if there are duplicate keys

Filter array of nested object using javascript

I want to filter specific object using nested object element this
"token": "4f1f17f6503e4c5a3a269ecf93d6c92d"
This my data:
const data = [
{
name: "test",
token: {
expiryTime: "2021-09-24T12:27:30.654Z",
purpose: "ForgotPassword3",
token: "4f1f17f6503e4c5a3a269ecf93d6c92d",
},
user_id: "acaacc940c9ebfe798dee68acf5c",
zipcode: "",
},
{
name: "df ",
token: null,
user_id: "e0efe9810ca289ccd590bce48051",
zipcode: "",
},
{
name: "Io",
phone: "88888888",
state: "NY",
token: null,
user_id: "c88ce38d0c86f786c3a4b0f9f967",
zipcode: "13201",
},
];
Expected output is:
Data array inside the first object of token using filter object. Below given expected out.
const data = [
{
name: "test",
token: {
expiryTime: "2021-09-24T12:27:30.654Z",
purpose: "ForgotPassword3",
token: "4f1f17f6503e4c5a3a269ecf93d6c92d",
},
user_id: "acaacc940c9ebfe798dee68acf5c",
zipcode: "",
},
];
If you want a specific object, you could use find instead of filter. find will return the first element which verifies the condition specified to the find method where as the filter method is used to filters all the elements and returns all the element that matches the condition withing an array.
*You need to add the optional chaining ?. because the token object might be null like you have in some of your data
here both examples:
const data = [
{
"name": "test",
"token": {
"expiryTime": "2021-09-24T12:27:30.654Z",
"purpose": "ForgotPassword3",
"token": "4f1f17f6503e4c5a3a269ecf93d6c92d"
},
"user_id": "acaacc940c9ebfe798dee68acf5c",
"zipcode": ""
},
{
"name": "df ",
"token": null,
"user_id": "e0efe9810ca289ccd590bce48051",
"zipcode": ""
},
{
"name": "Io",
"phone": "88888888",
"state": "NY",
"token": null,
"user_id": "c88ce38d0c86f786c3a4b0f9f967",
"zipcode": "13201"
}
]
const resFilter = data.filter(x => x.token?.token === "4f1f17f6503e4c5a3a269ecf93d6c92d");
console.log(resFilter);
const resObj = data.find(x => x.token?.token === "4f1f17f6503e4c5a3a269ecf93d6c92d");
console.log(resObj);
You must use the following code
const finded = data.filter(user => user?.token?.token ==="value"})
console.log(finded);

flatten array for Flatlist, React Native

so I'm working on an app in which I receive an array from getDerivedStateFromProps, and with that set the state of list, this is an example of the array:
const data = [
[
{
"exerciseName": {
"exerciseName": "Barbell Bench Press",
},
"key": 0.4867576438357962,
"numOfSets": 1,
"paddingBottom": 30,
"reps": "",
"reps2": "",
"reps3": "",
"reps4": "",
"sets": "",
"sets2": "",
"sets3": "",
"sets4": "",
"weigth": "",
"weigth2": "",
"weigth3": "",
"weigth4": "",
},
],
]
as you can see is a nested array and that's probably why it doesn't let me display it in the Flatlist. This is the function I use to get the list:
class mondayExercises extends Component {
constructor(props) {
super(props);
this.state = {
list: [],
}; }
static getDerivedStateFromProps(props, state) {
if (props?.list) {
const mergedArray = [].concat.apply([], props.list);
const flatten = mergedArray.flat(1);
return {
list: [...state.list, flatten],
};
}
return null;
}
I already managed to merge the arrays together, but is there a way to flatten it without changing the entire code of the app?

Iterate over json file in Vue

I'm having hard time in success to iterate over my external json file in Vue.
I'm importing the file like this:
import json from '../../public/platform.json'
export default {
data: () => ({
currentPage: 0,
brand: '',
platform: '',
affiliate: '',
myJson: json,
}),
Json file looking like this:
{
"Example": {
"Username": "",
"Password": "",
"AffiliateID": "",
"GI": "",
"CI": "",
"freeTextArea": ""
},
"ExampleTwo": {
"Username": "",
"Password": "",
"freeTextArea": ""
}
}
My goal is to do as follows:
I want to check if the "platform" from data is matching "Example" or "ExampleTwo" and if it does, I want to access the fields within either of them.
How can I do it?
You can use a computed property as follows:
computed: {
myPlatform: function () { return json[this.platform] || {}; },
}
Here is a demo: https://codesandbox.io/s/clever-gould-3hkbl?fontsize=14&hidenavigation=1&theme=dark

Modify Object literal data and wrap it in the array

I have an object literal or like a json file which has data in it, what I want is to wrap the SMBPremium and MAX data inside an array so that I can target by accessing its index. How Can I modify my object literal to an array so that I can target SMBPremium and MAX. Kinda like this.
productMap['TEC0'][1].productName;
This is my json
var productMap = {
"TEC0": {
"SMBPremium" : {
"productName": "Wilson",
"panelClass": "WilsonClass",
"fullinfoClass": "Wilsonfull",
"productPageLink": "",
"panelPageLinkGA": "",
"fullPageLinkGA": "",
"notifLinkDanger" : {
"linkPrimary" : "",
"linkSecondary" : ""
},
"notifLinkRed" : {
"linkPrimary" : "",
"linkSecondary" : ""
},
"notifLinkInfo" : "",
"notifLinkWarning" : "",
"notifLinkSuccess" : ""
},
"MAX": {
"productName": "Spalding",
"panelClass": "spalding",
"fullinfoClass": "spalding",
"productPageLink": "",
"panelPageLinkGA": "",
"fullPageLinkGA": "",
"notifLinkDanger" : {
"linkPrimary" : "",
"linkSecondary" : ""
},
"notifLinkRed" : {
"linkPrimary" : "",
"linkSecondary" : ""
},
"notifLinkInfo" : "",
"notifLinkWarning" : "",
"notifLinkSuccess" : ""
}
}
};
Tranform with array.map:
productMap2 = {};
productMap2.TEC0 = Object.keys(productMap['TEC0']).map(key => productMap['TEC0'][key]);
Then you can access productName property for each element:
productMap2.TEC0[1].productName
You can recreate the object productMap formatted like you wish:
// Every object is a map:
var tec0 = productMap['TEC0'];
var keys = Object.keys(tec0);
var array = [];
for(var i=0; i<keys.length; i++) {
var key = keys[i];
var value = tec0[key];
array.push(value);
}
var newProductMap = {'TEC0': array};
alert(newProductMap['TEC0'][1].productName);
NOTE: Faly's answer is far more elegant. Just be carefull at browser compatibility with arrow functions (IE does not support for example).
Idem for Ammar's answer, not supported by IE.
Use Object.values() method:
productMap["TEC0"] = Object.values(productMap["TEC0"]);
try this
index = 1
productMap['TEC0'][Object.keys(productMap['TEC0'])[index]].productName;
Explanation
productMap['TEC0'] is an json object
Object.keys(productMap['TEC0']) - will return json object keys as array.
in this example like this ["SMBPremium", "MAX"]
Object.keys(productMap['TEC0'])[index] - will return key name based
on index passed.
productMap['TEC0'][key_name] - will fetch json object based
key_name got from previous state.
You could map the items to an index of the wanted keys array.
var productMap = { TEC0: { SMBPremium: { productName: "Wilson", panelClass: "WilsonClass", fullinfoClass: "Wilsonfull", productPageLink: "", panelPageLinkGA: "", fullPageLinkGA: "", notifLinkDanger: { linkPrimary: "", linkSecondary: "" }, notifLinkRed: { linkPrimary: "", linkSecondary: "" }, notifLinkInfo: "", notifLinkWarning: "", notifLinkSuccess: "" }, MAX: { productName: "Spalding", panelClass: "spalding", fullinfoClass: "spalding", productPageLink: "", panelPageLinkGA: "", fullPageLinkGA: "", notifLinkDanger: { linkPrimary: "", linkSecondary: "" }, notifLinkRed: { linkPrimary: "", linkSecondary: "" }, notifLinkInfo: "", notifLinkWarning: "", notifLinkSuccess: "" } } },
keys = ['SMBPremium', 'MAX'];
keys.forEach((k, i) => productMap.TEC0[i] = productMap.TEC0[k]);
console.log(productMap['TEC0'][0].productName);

Categories

Resources