Split a JSON object by parameters - arrays

I have a JSON Object defined in Typescript, I want to split it into parts but I can only get the keys:
This is my JSON object:
let data = {
"dataTest": "data1,data2,data3",
"insTest": "ins1,ins2,ins3",
"serTest": "ser1,ser2,ser3"
}
This is what I do to loop through it:
for (let key of Object.keys(data)) {
console.log(key)
}
This is what I get:
1º //dataTest
2º //insTest
3º //serTest
This is what I want to get:
1º //dataTest: "data1,data2,data3"
2º //insTest: "ins1,ins2,ins3"
3º //serTest: "ser1,ser2,ser3"
Upgrade
Is it also possible to get the concatenation of all the values in a single array?
Example:
data1,data2,data3,ins1,ins2,ins3,ser1,ser2,ser3

Use Object.entries().
The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
const data = {
dataTest: "data1,data2,data3",
insTest: "ins1,ins2,ins3",
serTest: "ser1,ser2,ser3"
};
const entries = Object.entries(data);
entries.forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});

You can get the required value using Object.entries().
let data = {
"dataTest": "data1,data2,data3",
"insTest": "ins1,ins2,ins3",
"serTest": "ser1,ser2,ser3"
}
Object.entries(data).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});

Here is another way
for(let key in data) {
console.log(key + ': ' + '"' + data[key] + '"');
}
using Template literals
for(let key in data) {
console.log(`${key}: "${data[key]}"`);
}

Related

Iterating through a JSON array and returning a subset of elements

I'm new to JS and trying to figure out how to iterate through a json array and return only a subset of elements. Specifically I would like to know how to return only the 'first_name' and 'last_name' from the Mock data in the attached code snippet. It seems like it should be straightforward but I'm scratching my head.
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}]
people.forEach(person => {
for (let key in person) {
console.log(`${key} => ${person[key]}`);
}
Use the element names
people.forEach(person => {
console.log(JSON.stringify(person) + "\n");
console.log(person["first_name"], person["last_name"], "\n");
});
Produces this output:
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"}
Talbert Kohnert
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"}
Ruthie McKleod
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}
Lenore Foister
You can try Object destructuring assignment of ES6 to achieve the requirement.
Working Demo :
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}];
let res = people.map(({first_name, last_name}) => first_name + ' ' + last_name);
console.log(res);
There are numerous way of achieving this output. One of most frequently used method is using map() of es6.
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}]
//by map method
people.map((person,index)=>{
console.log(`${person.first_name} ${person.last_name}`)
})
// by forEach
people.forEach(person => {
console.log(`${person.first_name} ${person.last_name}`)
}
you can achieve this by using the map function.
map lets you iterate over each item in the array and return a new value for each iteration while returning a new array, so for your case:
let people = [
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}
]
const newArray = people.map((person) => {
return {
first_name: person.first_name,
last_name: person.last_name
}
})
console.log(newArray)
here you get a new array with just the properties you need.

AWS GraphQL JSON string formatting

I'm attempting to create an object value to pass into DynamoDB using AWS AppSync and GraphQL. I'm very close to what I need but I'm stumbling on nested JSON.
Let's say I have an array:
let officers = [{"id":"0","IgRole":"Role1","IgName":"testname1","IgEmail":"testemail1","IgPhone":"testphone1","IgStart":"teststart1","IgEnd":"testend1"},
{"id":"1","IgRole":"Role2","IgName":"testname2","IgEmail":"testemail2","IgPhone":"testphone2","IgStart":"teststart2","IgEnd":"testend2"}]
I now want to create an object with each of the array values as a child object so, I do this:
for (let i in officers) {
officersJson['"' + officers[i].IgRole + '"'] = '{"Name":"' + officers[i].IgName + '","Email":"' + officers[i].IgEmail + '","Phone":"' + officers[i].IgPhone + '","Date commenced":"' + officers[i].IgStart + '","Date to end":"' + officers[i].IgEnd + '"}';
}
Here are the results:
Object {
"Role1": "{'Name':'testname1','Email':'testemail1','Phone':'testphone1','Date commenced':'teststart1','Date to end':'testend1'}",
"Role2": "{'Name':'testname2','Email':'testemail2','Phone':'testphone2','Date commenced':'teststart2','Date to end':'testend2'}"
}
I think the problem is that the each entire key / value is not in string format. If you look at
"Role1": "{......
you can see that the string breaks.
and this is the response from AWS:
Variable 'Officers' has an invalid value. Unable to parse {\"Role1\"={\"Nam
See the = sign
How can I format the object into a complete JSON string? I was fairly pleased I managed to get anywhere near the format I needed but this last bit has me stumped.
Finally worked it out. I needed a slightly different approach. Posting it in case it helps anyone else:
Firstly I created an array of roles, as this will be the keys for the value objects:
for (let i in officers) {
roles.push(officers[i].IgRole);
}
I then created a new array.
let arrOfficers = [];
for (let i in officers) {
arrOfficers.push(officers[i]);
}
I then use a function to create objects from an array:
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
let key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
let newresult = groupBy(arrOfficers, "IgRole");
Finally I create my object and then stringify it:
let officersJson = {};
for (let i in roles) {
officersJson[roles[i]] = newresult[roles[i]][0];
}
theObjectIwant = JSON.stringify(officersJson)

Fetch Data from nested props in ReactJS

I am uploading the data from excel file using react-excel-renderer, storing the excel render response containing column & rows response in state and passing to other component.
Expected Use-case result:- I am fetching the data from excel using render storing the values in states(rows). I am passing the state to other component where i need these values to pass in API .
The data stored is in nested form. Can you please let me know how to get data separately stored under array in props. Attached is the screenshot.
Excel Render code:-
changeHandler(event) {
let fileObj = event.target.files[0];
//just pass the fileObj as parameter
ExcelRenderer(fileObj, (err, resp) => {
if (err) {
console.log(err);
} else {
this.setState({
cols: resp.cols,
rows: resp.rows,
});
}
});
}
Code to fetch the prop data:-
for (let i = 0; i < this.props.data.length; i++) {
let stDate = this.props.data[i].startDate;let TripName = this.props.data[i].TripName;
let totalFare = this.props.data[i].totalFare;
let FirstName = this.props.data[i].FirstName;
let LastName = this.props.data[i].LastName;
let Currency = this.props.data[i].Currency;
}
You can use an Array method
Still not 100% sure what your final data should look like, but it feels like you're using 2 arrays. 1 as the key and 1 as the value.
So to combine these 2 we can use Reduce
const keys = data[0];
const values = data[1];
keys.reduce((acc, keys, index) => {
return {...acc, [key]: values[index]}
}, {})
That will return an object of key values.

Values are not stored in array AsyncStorage react native

I am trying to store values in AsyncStorage as array, but values are not saving there and getting nothing when i try to get the values from array.Any help would be appreciated.Thank you in advance,here is my code :
let searchString = this.state.inputValue
AsyncStorage.getItem('searches', (res) => {
var searches
if (res === null) {
searches = []
}else {
searches = JSON.parse(res)
}
searches.push({
searchString: searchString
})
AsyncStorage.setItem('searches', JSON.stringify(searches), (res) => {
console.log('====FirstPage====setItem==async==='+res)
})
});
//getting values from asyncstorage :
AsyncStorage.getItem('searches', (res) => {console.log('===res==='+res)})
Please try this
AsyncStorage.getItem("searches").then((value) => {
this.setState({"searches": value});
}).done();
Also see
https://www.thepolyglotdeveloper.com/2015/09/saving-data-in-your-react-native-mobile-application/
You can store the data as following:
AsyncStorage.setItem('searches', JSON.stringify(searchString));
In order to fetch/get, you can do that using following:
AsyncStorage.getItem('searches', (err, result) => { // err indicating the error
console.log("Storage Data(String):", result); // print is string format
console.log("Storage Data(Object):", JSON.parse(result)); // print is json format
})

react , using <br> inside .map inside for (object)

I know in react you can't use <html> like strings, i'm looking for a solution but i don't see clear, how in this complex logic you can to insert a <br/> object and not like string, because variable 'newvalue' need to store and conditionally add br to separate elements in rows.
let values = JSON.parse(value);
let newvalue = '';
values.map((item) => {
for (const key in listViewField.subfields) {
let nameField = key;
if (typeof item[nameField] !=='undefined') {
newvalue += item[nameField]+ ' ';
}
}
// if (newvalue.trim() !=='') newvalue += '<br/>'; // doesn't work
});
value = newvalue;
return <div key={keyIndex}>{value}</div>;
Rather than using map, you can just iterate over your values and push them into an array.
let values = JSON.parse(value);
let contents = [];
for (let value of values) {
contents.push(<span key={value.key}>{value.name}</span>);
if (value.condition) {
contents.push(<br key={`${value.key}-br`} />);
}
});
return <div>{contents}</div>;
Don't forget to add a unique key to each item.
To add different option, if you want to use it with map and your item is simple string, then you can do something like this.
items.map((item, key) => {
<span style={{whiteSpace: 'pre'}} key={key}>{item + '\n'}</span>
});
Note that I have added style={{whiteSpace: 'pre'}} and + \n

Resources