I'm trying to manipulate this array and play with parse, push and save data commands. but for some reason is not reading.
Any help?
I'm super new to it and just trying to practice.
Should be an array of objects.
var employeeString = [
{ first_name: 'Josh', last_name:'Neil', nationality:'Indian'},
{ first_name: 'Brian', last_name:'Cok', nationality:'Canadian'},
{ first_name: 'Katja', last_name:'Fanta', nationality:'German'}
];
var jsonValues = JSON.stringify(employeeString);
current_values = JSON.parse(jsonValues);
var nationality = [];
//console.log (current_values);
for ( i = 0; i < current_values.length; i++) {
var currentItem = current_values[i]
var first_name = currentItem['first_name'];
var last_name = currentItem['last_name'];
//push value into array
nationality.push(currentItem['nationality']);
if (currentItem == 'first_name' || currentItem == 'last_name') {
return id[i+1];
}
}
console.log (first_name , last_name);
You don't need to parse the already JSON object.
For example JSON.parse('[{x:10},{y:20}]'); will return JSON object from the string. This step is required to access the value of x and y, which are in string form as you can see '' around it. But in your case, you already got a JSON Object you don't need to parse it again.
Further in console.log if you want to print first_name, do not add '' around it. Here is your working code
var current_values = [
{ first_name: 'Josh', last_name: 'Neil', Nationality: 'Indian' },
{ first_name: 'Brian', last_name: 'Cok', Nationality: 'Canadian' },
{ first_name: 'Katja', last_name: 'Fanta', Nationality: 'German' }
];
// current_values = JSON.parse(employeeString);
// console.log(current_values);
for (i = 0; i < current_values.length; i++) {
var currentItem = current_values[i]
var first_name = currentItem['first_name'];
var last_name = currentItem['last_name'];
console.log(first_name, last_name);
}
The JSON.parse method accepts a string, but you're giving it an array of objects.
var values = JSON.parse("[{'first_name': 'Josh', ...}, ...]");
Would work better.
In general, parsing will convert a string to objects. http://www.willamette.edu/~fruehr/haskell/seuss.html
The data type for employeeString is Array, but JSON.parse() is supposed to parse JSON data. So, you can first change employeeString into a JSON data before parse it.
You don't need to JSON.parse(employeeString), since it is already an object.
JSON.parse is used to create objects from their string representation, e.g. parse the string '{"prop":42}' to an actual object with a property prop and its value being 42. Since employeeString in your code is already an object, you don't need to JSON.parse it again.
BTW, you probably meant this:
// notice that this is now an actual string
var employeeString = `[
{ first_name: 'Josh', last_name:'Neil', Nationality:'Indian'},
{ first_name: 'Brian', last_name:'Cok', Nationality:'Canadian'},
{ first_name: 'Katja', last_name:'Fanta', Nationality:'German'}
]`;
Related
I am trying below code but its not working so first am trying to get a person department Name currently, hard coded it to check
var arr=[]
let CurrDept = "AB-CDE-F";
var Detept=CurrDept.substring(0,5);
arr.push(Detept)
Now in below line of code i am trying this line so it should exclude all results which start from AB-CD
var Userprofiledept=data.value[0].UserId.Department;
const isInArray = arr.indexOf(Userprofiledept) > -1;
isInArray should be false which can be put in my condition but it always give true
Can anyone help ?
So current user department may be AB-CDE-F and data i am getting from my rest call may have lots of department for many users AB-CDE-F,AB-CDE-F,AB-CDE,AB-CD,AB-C
so only want to exclude results which are AB-CDE-F,AB-CDE-F,AB-CDE,AB-CD as they are starting with AB-CD
You can use Array.prototype.filter and String.prototype.startsWith.
const
data = {value: [{ UserId: { ID: 14, Email: "sdfds", Department: "AB-CD-EF" } }, { UserId: { ID: 14, Email: "sdfds", Department: "AB-CD" } }, { UserId: { ID: 14, Email: "sdfds", Department: "AB-C" } }]},
discard = "AB-CD",
res = data.value.filter((v) => !v.UserId.Department.startsWith(discard));
console.log(res);
You could move the functionality into a function and check if the substring exists and add, if necessary.
const
add = string => {
string = string.slice(0, 5);
if (array.includes(string)) return;
array.push(string);
}
array = [];
add('AB-CDE-F');
console.log(array);
add('AB-CDE-F');
console.log(array);
add('AB-CDE');
console.log(array);
I have an array of objects that looks like:
{
name: 'steve',
plaintiff:'IRS'
amount: 5000,
otherliens:[
{
amount:5000,
plaintiff:'irs'
},
{amount:5000,
plaintiff:'irs'
}
]
}
i need to send this as a csv so i need to map and iterate over this subarray and flatten it into them ain object like so:
{
name:'steve',
plaintiff:'irs',
amount:5000,
plaintiff2:'irs',
amount2:5000,
plaintiff3:'irs',
amount3:5000
}
the code i use to normally do this process is by mapping the contents of the original array into a new array with arr.map(a,i =>{ a[i] ? a[i].amount = a[i].amount }) i am able to work the the subarrays that are string based by flat guessing a number of entries (see phones and emails) because if i return null it just returns blank, which in the csv isnt the worst thing. but i cannot do the same because accessing a sub property of an element that doesnt exist obviously wont work. So here is the map im using where emailAddresses is a string array, phoneNumbers is a string array and otherliens is an object array.
any help would be appreciated and bear in mind because it is bulk data transfer and csvs that will have a fixed number of columns in the end, i dont mind null values, so i guess you would take the longest subarray length and use that in all the other objects.
Full code
prospects.map((list, i) => {
result[i]
? (result[i].fullName = list.fullName)
(result[i].First_Name = list.firstName)
(result[i].Last_Name = list.lastName)
(result[i].Delivery_Address = list.deliveryAddress)
(result[i].City = list.city)
(result[i].State = list.state)
(result[i].Zip_4 = list.zip4)
(result[i].County = list.county)
(result[i].plaintiff= list.plaintiff)
(result[i].Amount = list.amount)
(result[i].age = list.age)
(result[i].dob= list.dob)
(result[i].snn= list.ssn)
(result[i].plaintiff2= list.otherliens[1].plaintiff )
(result[i].filingDate2= list.otherliens[1].filingDate)
(result[i].amount2= list.otherliens[1].amount )
(result[i].plaintiff3= list.otherliens[2].plaintiff)
(result[i].filingDate3= list.otherliens[2].filingDate )
(result[i].amount3= list.otherliens[2].amount )
(result[i].amount4= list.otherliens[3].amount)
(result[i].plaintiff4= list.otherliens[3].plaintiff )
(result[i].filingDate4= list.otherliens[3].filingDate )
(result[i].phone1 = list.phones[0])
(result[i].phone2 = list.phones[1])
(result[i].phone3 = list.phones[2])
(result[i].phone4 = list.phones[3])
(result[i].phone5 = list.phones[4])
(result[i].phone6 = list.phones[5])
(result[i].phone7 = list.phones[6])
(result[i].phone8 = list.phones[7])
(result[i].phone9 = list.phones[8])
(result[i].emailAddress1 = list.emailAddresses[0])
(result[i].emailAddress2 = list.emailAddresses[1])
(result[i].emailAddress3 = list.emailAddresses[2])
(result[i].emailAddress4 = list.emailAddresses[3])
(result[i].emailAddress5 = list.emailAddresses[4])
(result[i].emailAddress6 = list.emailAddresses[5])
(result[i].emailAddress7 = list.emailAddresses[6])
: (result[i] = {
Full_Name: list.fullName ,
First_Name: list.firstName,
Last_Name: list.lastName,
Delivery_Address: list.deliveryAddress,
City: list.city,
State: list.state,
Zip_4: list.zip4,
County: list.county,
dob: list.dob,
ssn:list.ssn,
age:list.age,
Amount: list.amount,
plaintiff: list.plaintiff,
filingDate: list.filingDate,
phone1:list.phones[0],
phone2:list.phones[1],
phone3:list.phones[3],
phone4:list.phones[4],
phone5:list.phones[5],
phone6:list.phones[6],
phone7:list.phones[7],
phone8:list.phones[8],
emailAddress1:list.emailAddresses[0],
emailAddress2:list.emailAddresses[1],
emailAddress3:list.emailAddresses[2],
emailAddress4:list.emailAddresses[3],
emailAddress5:list.emailAddresses[4],
emailAddress6:list.emailAddresses[5],
plaintiff2: list.otherliens[1].plaintiff,
amount2: list.otherliens[1].amount,
filingDate2: list.otherliens[1].filingDate,
plaintiff3: list.otherliens[2].plaintiff,
filingDate3: list.otherliens[2].filingDate,
amount3: list.otherliens[2].amount,
plaintiff4: list.otherliens[3].plaintiff,
amount4: list.otherliens[3].amount,
filingDate4: list.otherliens[3].filingDate,
})
} );
Use loops to assign properties from the nested arrays, rather than hard-coding the number of items.
I also don't see the need for the conditional expression. Since each input element maps directly to an output element, there won't already be result[i] that needs to be updated.
result = prospects.map(({fullName, firstName, lastName, deliveryAddress, city, state,zip4, county, plaintiff, amount, age, dob, ssn, otherliens, phones, emailAddresses}) => {
let obj = {
fullName: fullName,
First_Name: firstName,
Last_Name: lastName,
Delivery_Address: deliveryAddress,
City: city,
State: state,
Zip_4: zip4,
County: county,
plaintiff: plaintiff,
Amount: amount,
age: age,
dob: dob,
ssn: ssn
};
otherliens.forEach(({plaintiff, amount}, i) => {
obj[`plaintiff${i+2}`] = plaintiff;
obj[`amount${i+1}`] = amount;
});
phones.forEach((phone, i) => obj[`phone${i+1}`] = phone);
emailAddresses.forEach((addr, i) => obj[`emailAddress${i+1}`] = addr);
return obj;
})
I have problems with Object.assign and ... spread operator. I need to process values (object with name and value tha are objects).
Example my values object:
{
id: "12",
name: "Hotel MESSI",
email: "myemail#aol.com",
phone: "+001060666661",
otherfields: "{
country: 'ZW',
city: 'Zurick'
}"
}
otherfields comes from graphql , so it's string, i must convert to object.
With my process I look for this result:
{
id: "12",
name: "Hotel MESSI",
email: "myemail#aol.com",
phone: "+001060666661",
country: 'ZW',
city: 'Zurick'
}
The code have more code that I paste here, there is a lot of controls for values and conversion but mainly, the idea is reassing values,
With these two case assign to the same variable is not working:
Case 1, with object.assign
processValues = (values)=>
let newValues = {...values}; //
for (const fieldName in Tables[table].fields) {
let value = values[fieldName];
value = JSON.parse(value);
newValues = { ...newValues, ...value};
console.error('after mix',newValues);
Case 2, with object.assign
processValues = (values)=>
let newValues = Object.assign({}, values}; //
for (const fieldName in Tables[table].fields) {
let value = values[fieldName];
value = JSON.parse(value);
newValues = Object.assign( newValues, value};
console.error('after mix',newValues);
How it's works, when I use a new variable, by example:
newValues2 = Object.assign( newValues, value};
but my idea is not use another variable because , i need to get values and set values for the original variable 'newValues' , if I use another variable the code would be more cumbersome.
I'm using in a project with create-react-app. I don't know if it's a problem with babel, because Object.assign and spread operator are not inmmutable; or yes ?
INFO:
Tables[table].fields is a object with definition por my table structure, there therea lot of rules, but basically i need to know why object and ... does not work
The use of JSON.stringify will not help, as this will produce a JSON string, which will have an entirely different behaviour when spreading it (you get the individual characters of that string).
Here is how you can achieve the result with "otherfields" as the special field (you can add other fields in the array I have used):
const processValues = values =>
Object.assign({}, ...Object.entries(values).map( ([key, val]) =>
["otherfields"].includes(key) ? val : { [key]: val }
));
// Example:
const values = {
id: "12",
name: "Hotel MESSI",
email: "myemail#aol.com",
phone: "+001060666661",
otherfields: {
country: 'ZW',
city: 'Zurick'
}
};
const result = processValues(values);
console.log(result);
The first argument to assign is the target. So it's going to get changed. You can simply pass an empty object for your target if you don't want any of the sources to change.
When you are using first argument as {} then no value will change.
For more please refer it.
https://wecodetheweb.com/2016/02/12/immutable-javascript-using-es6-and-beyond/
I am trying to compare two objects and construct a third one if the value stored in a property of one is different than the other. If not I am storing an empty string. The way am doing it in my opinion is super inefficient and non sustainable. This wont work if the keys change or their number increases. I have to be able to do this programmatically with pure JS, no jQuery:
var staleProfile = {
firstName: 'john',
lastName: 'smith',
email: 'js#gmail.com'
}
var CurrentCustomer = {};
CurrentCustomer.profile = {
firstName: 'paul',
lastName: 'smith',
email: 'js#yahoo.com'
}
var returnObj = {};
returnObj.firstName = staleProfile.firstName != CurrentCustomer.profile.firstName ? CurrentCustomer.profile.firstName : ''
returnObj.lastName = staleProfile.lastName != CurrentCustomer.profile.lastName ? CurrentCustomer.profile.lastName : ''
returnObj.email = staleProfile.email != CurrentCustomer.profile.email ? CurrentCustomer.profile.email : ''
This searches for all the object keys in the CurrentCustomer.profile and checks for differences to the staleProfile. It adds keys to the diff, that only exist in object1 but not in object0, but doesn't take care of keys that are removed from object0to object1.
var staleProfile = {
firstName: 'john',
lastName: 'smith',
email: 'js#gmail.com',
key0: 'value0'
}
var CurrentCustomer = {};
CurrentCustomer.profile = {
firstName: 'paul',
lastName: 'smith',
email: 'js#yahoo.com',
key1: 'value1'
}
function createDiffObject(object0, object1) {
var diff = {};
Object.keys(object1).forEach(function(key) {
if (!object0.hasOwnProperty(key) || object0[key] != object1[key]) {
diff[key] = object1[key];
} else {
diff[key] = '';
}
});
return diff;
}
console.log(createDiffObject(staleProfile, CurrentCustomer.profile));
// output:
/*
{ firstName: 'paul',
lastName: '',
email: 'js#yahoo.com',
key1: 'value1' }
*/
An option would be to get all the keys present in your object using Object.keys(staleProfile).
After this you can loop through the keys and compare values. See an example down below.
var keys = Object.keys(staleProfile),
i, j,
comparedObject = {},
key,
CurrentCustomer = {
a:a,
b:b,
c:c
};
for (i = 0, j = keys.length; i < j; i++) {
key = keys[i];
if (staleProfile[key] === CurrentCustomer[key]) {
comparedObject[key] === CurrentCustomer[key];
} else {
comparedObject[key] === '';
}
}
One way to do it is to make a small helper function to assign each property (or empty string):
// NOTE: staleProfile and CurrentCustomer are assumed to be in the scope above
// If this could be an issue, just pass them as parameters
function getProp(prop) {
let staleProp = staleProfile[prop];
let currProp = CurrentCustomer.profile[prop];
return staleProp != currProp ? currProp : '';
}
And then use it like:
let returnObj = {
firstName : getProp('firstName'),
lastName : getProp('lastName'),
email : getProp('email')
}
Running Example
var staleProfile = {
firstName: 'john',
lastName: 'smith',
email: 'js#gmail.com'
}
var CurrentCustomer = {};
CurrentCustomer.profile = {
firstName: 'paul',
lastName: 'smith',
email: 'js#yahoo.com'
}
function getProp(prop) {
let staleProp = staleProfile[prop];
let currProp = CurrentCustomer.profile[prop];
return staleProp != currProp ? currProp : '';
}
let returnObj = {
firstName: getProp('firstName'),
lastName: getProp('lastName'),
email: getProp('email')
}
console.log(returnObj);
The advantage of this helper function is that, in case you need to update your strategy for replacement of a missing value, you only have to do it in one place.
Furthermore, you could have an array of keys you would like to extract:
let keys = ['firstName', 'lastName', 'email'];
Or perhaps extract all using Object.keys:
let keys = Object.keys(staleProfile);
And then you can store the keys using the getProp function:
keys.forEach(k => {
returnObj[k] = getProp(k);
});
This would make adding/removing properties simply a matter of the current content the keys array. When you need to remove or add a property, you can either update the keys array in the first example, or update the staleProfile in the second example and let Object.keys return the values for you. Either way, with one small change you can add/remove properties.
Running example:
var staleProfile = {
firstName: 'john',
lastName: 'smith',
email: 'js#gmail.com'
}
var CurrentCustomer = {};
CurrentCustomer.profile = {
firstName: 'paul',
lastName: 'smith',
email: 'js#yahoo.com'
}
function getProp(prop) {
let staleProp = staleProfile[prop];
let currProp = CurrentCustomer.profile[prop];
return staleProp != currProp ? currProp : '';
}
let keys = Object.keys(staleProfile);
let returnObj = {};
keys.forEach(k => {
returnObj[k] = getProp(k);
});
console.log(returnObj);
Note: James Thorpe made a good observation in the comment.
what if one of the future properties you speak of could validly hold an empty string? In that case, you won't know if it's been updated to a an empty string or is unchanged. You may want to consider using null for unchanged items
I've been trying to use the approach suggested by another SO-User: https://stackoverflow.com/a/1820837/1324861
But without luck. Basically, I have a large JSON Object that I transformed into a string using JSON.stringify() in order to execute a regexp pattern against. My idea is to return everything between { } if my search term "soccer" is found anywhere between the curly braces.
My data could look like this:
{
{
User: "Peter",
Hobbies: "Soccer, Football, ...",
more...
},
{
User: "Simon",
Hobbies: "Pingpong, Soccer, Badminton",
more...
}
}
So if I searched for 'soccer' in my stringified JSON Object I'd like to get back the entire info on the user. How can I do this?
You could inspire from this (without transforming your json into string):
var myData = [
{
User: "Peter",
Hobbies: "Soccer, Football, ..."
},
{
User: "Simon",
Hobbies: "Pingpong, Soccer, Badminton"
}
];
var results = "";
for (var i = 0; i < myData.length; i++) {
if (myData[i]["Hobbies"].indexOf("Soccer") != -1) {
results += JSON.stringify(myData [i]) + "\n";
}
}
alert(results);
Not that it doesn't make sense to stringify a JSON object to apply a regex on it (shudder) but hey, it's your CPU... You could use something like this:
\{[^{]+soccer[^}]+}
This should catch what you're looking for. But... Parsing JSON with regexes... Nononono...
Something like "{[^}]*(S|s)occer[^}]*}"
var json = [
{
User: "Peter",
Hobbies: "Soccer, Football, ..."
},
{
User: "Simon",
Hobbies: "Pingpong, Badminton"
}
];
var jsonString = JSON.stringify(json);
var regEx = /(\{.*?Soccer.*?\})/;
var user = jsonString.match(regEx)[1];
document.write(user);