How to Iterate Over Array and Stringify a Property - javascript

I am trying to accumulate a property of an array and write save it back to the array as a string to later be parsed with JSON.parse.
In the initial data set the items property is an array.
I would like to restructure the data such that items is a string of the objects.
Given something like:
[{
{
"n":"1",
"items": [0: "{"id":"id1","desc":"description1"}",
1: "{"id":"id2","desc":"description2"}"
2: "{"id":"id3","desc":"description3"}"]
},
{
"n":"2",
"items": [0: "{"id":"id4","desc":"description4"}",
1: "{"id":"id5","desc":"description5"}"
2: "{"id":"id6","desc":"description6"}"]
}
}]
Convert to:
[{
{
"n":"1",
"items": "[{"id":"id1","desc":"description1"}","{"id":"id2","desc":"description2"}","{"id":"id3","desc":"description3"}]"
},
{
"n":"2",
"items": "[{"id":"id4","desc":"description4"}","{"id":"id5","desc":"description5"}", "{"id":"id6","desc":"description6"}]"
}
}]

I had to clean up your data, so I will go with the assumption that the data structure I set below is what you actually meant.
const data = [
{
"n":"1",
"items": [
{"id":"id1","desc":"description1"},
{"id":"id2","desc":"description2"},
{"id":"id3","desc":"description3"}
]
},
{
"n":"2",
"items": [
{"id":"id4","desc":"description4"},
{"id":"id5","desc":"description5"},
{"id":"id6","desc":"description6"}
]
}
];
const newData = data.map(val => {
return Object.assign({}, val, {
items: JSON.stringify(val.items)
});
});
console.log(newData);

arr.map(({ items, ...rest }) => ({ items: JSON.stringify(items), ...rest }));

Related

filter array of object using lodash or underscore

I have the following structure and this data is displaying as the list in (as in my given screenshot), here I want to add a filter, like say If I put "a" in my search box it should display all the names which has "a" and when I type the full name like "atewart Bower" it should only show the one list. So far I doing this
const searchContact = newData.filter(d => { // here newData is my arr of objs
let alphabet = d.alpha.toLowerCase();
return alphabet.includes(this.state.searchUserName.toLowerCase())
})
it is returning on the basis of "alpha" not "name" inside the users array. I was trying to use Lodash and underscore.js, but didn't find what I want to achieve there too.
I tried this code of Lodash
const dd = _.filter(newData, { users: [ { name: this.state.searchUserName } ]});
but it also return the array of object when I write the full name like when this.state.searchUserName = atewart Bower
[
{
alpha: "a",
users: [
{
id: "1",
name: "atewart Bower"
},
{
id: "1",
name: "aatewart Bower"
},
]
},
{
alpha: "b",
users: [
{
id: "1",
name: "btewart Bower"
},
{
id: "1",
name: "bbtewart Bower"
},
]
}
]
It is filtering on basis of alpha because inside the filter, we are using alpha value to check.
let alphabet = d.alpha.toLowerCase();
return alphabet.includes(this.state.searchUserName.toLowerCase())
To check inside the users array, you can do something like this
const getSearchedContacts = (newData, searchUserName) => {
const searchResults = [];
newData.forEach((item) => {
const users = item.users.filter(user => user.name.toLowerCase().startsWith(searchUserName.toLowerCase()));
if (users.length) searchResults.push({...item, users});
});
return searchResults;
};
getSearchedContacts(yourData, 'atewart Bower'); // Returns [{"alpha":"a","users":[{"id":"1","name":"atewart Bower"}]}]
Note: I'm using startsWith instead of includes because we want to return only one name when search string is for example "atewart Bower"

adding json key names to a json values and changing key names

I have a json string that is in the format:
[
{
clientIDs:
"WELL #6",
analyteIDs:
[
"7440-62-2",
"7440-28-0"
]
}
]
I need to convert this to:
[
{
header:
"WELL #6",
items:
[
header: "7440-62-2",
header: "7440-28-0"
]
}
]
The values without a key name are throwing me off.
Unfortunately js cannot store a key value arrays, instead you have to use an object storing key and value. So the closes result you can achieve is following:
[
{
header:
"WELL #6",
items:
[
{ header: "7440-62-2" },
{ header: "7440-28-0" }
]
}
]
For that your steps will be following:
Assuming you have an array of objects.
Assuming the keys you want to change are static and will always exist in the objects
const myObjects = [
{
clientIDs:
"WELL #6",
analyteIDs:
[
"7440-62-2",
"7440-28-0"
]
}
]
myObjects.map((myObj) => {
myObj['header'] = myObj.clientIDs;
myObj['items'] = myObj.analyteIDs.map((item) => {
return { header: item }
});
// Keep in mind, if keys are dynamic and does not exist in some objects then this will fail
delete myObj['clientIDs'];
delete myObj['analyteIDs'];
});
console.log(myObjects);

Creating an object from API data and adding it to an array dynamically

I have a data set that I'm pulling in from a database. It's one dimensional and I basically need to make it more structured. I refer to it as "flat".
I need to display a heading, and items under that heading that are related to the heading.
The data comes in as having and section_name (the heading) and item_name (items) and other data unique to each item like download URLs etc.
item_name(item)_______section_name(header)
first_________________Funds
second________________Funds
third_________________Funds
fourth________________Literature
fifth_________________Literature
sixth_________________Literature
seventh_______________Literature
eighth________________DueDilligence
I don't know what any of the names will be for the items or sections, or how many items, sections, or items per section. As I said, it's very flat. This needs to be fully dynamic which is why this is complicating things for me.
Here is what I've done.
API call to retrieve data. Store data in a state as an array (it comes in as an array of objects).
I create an empty array to store my newly structured data.
I loop through the data with a foreach.
I create a new object for my new data to add to the new array so I can loop over it later.
I first check to make sure the data exists.
To create the headers I check to see if my new empty array is actually empty OR my section_name is not the same as the last one.(in the original data array I got from the API call)
I store the section_names as an object in the new array (newArray.push(newObject)
I've gotten this far. Now I need to take the item_names that correlates to the section_names and store them in the object under each header name, or at least in the same index.
_generateInfo() {
let dataArray = this.state.stepTwoData
let newArray =[]
dataArray.forEach(function(item, index) {
let newObject = {}
if (index > 0) {
if (newArray.length === 0 || item.investor_portal_section_name !== dataArray[index -1].investor_portal_section_name) {
newObject["name"] = item.investor_portal_section_name
newObject["items"] = []
newArray.push(newObject)
}
})
console.log(newArray)
}
I tried pushing the items to the "number" array on my new object and that doesn't seem to work properly. Sometimes it will duplicate my newObject.name
Checking if the newObject.name === the section_names in the array and push it to the "number" array in my new object just creates new key-value pairs so it's still not correlating.
I tried looping through again in the if statement and if section_name === newObject.name then create a newObject and push it, but it would only push one of the items repeatedly instead of going through all of them.
I need to loop through and create a header (one header per different section_name). Then add each item that corresponds to the section_name to it. like this
[
{section_name(header): "Funds",
items: [
{
name: item_name,
sku: item_sku,
url: item_url
},
{
name: item_name,
sku: item_sku,
url: item_url
}]
},
{section_name(header):"Literature",
items: [
{name: item_name,
sku: item_sku,
url: item_url
},
{
name: item_name,
sku: item_sku,
url: item_url
}]}
]
Using associative array (dictionary) to segregate you data itmes by categories will do the job.
I've drafted some POC code that illustrates the idea. The key element there is buildAssociativeArray function
const raw_data = [
{item_name: "first", section_name: "Funds"},
{item_name: "second", section_name: "Funds"},
{item_name: "third", section_name: "Funds"},
{item_name: "fourth", section_name: "Literature"},
{item_name: "fifth", section_name: "Literature"},
{item_name: "sixth", section_name: "Literature"},
{item_name: "seventh", section_name: "Literature"},
{item_name: "eighth", section_name: "DueDilligence"},
]
function buildAssociativeArray(data) {
const dictionary = {};
for (var i = 0; i < data.length; i++) {
const item = data[i];
const section = item.section_name;
var dictEntry = dictionary[section];
if (!dictEntry) {
dictEntry = [];
dictionary[section] = dictEntry;
}
dictEntry.push({
name: item.item_name,
// other fields like sku: item_sku or url: item_url may follow here
});
}
return dictionary;
}
const dictionary = buildAssociativeArray(raw_data);
console.log(dictionary);
/*
At this point
dictionary == {
"Funds": [
{
"name": "first"
},
{
"name": "second"
},
{
"name": "third"
}
],
"Literature": [
{
"name": "fourth"
},
{
"name": "fifth"
},
{
"name": "sixth"
},
{
"name": "seventh"
}
],
"DueDilligence": [
{
"name": "eighth"
}
]
}
*/
// Associcative array dictionary itself allows to further solve you task using for (var key in dictionary) {...} operator
// If however you need to obtain the data structure looking exactly like the one in your question you may go further with following function
function transformAssociativeArray(dictionary) {
const array = [];
for (var key in dictionary) {
const items = dictionary[key];
const newEntry = {
section_name: key,
items: items,
}
array.push(newEntry);
}
return array;
}
const array = transformAssociativeArray(dictionary);
console.log(array);
/*
At this point
array == [
{
"section_name": "Funds",
"items": [
{
"name": "first"
},
{
"name": "second"
},
{
"name": "third"
}
]
},
{
"section_name": "Literature",
"items": [
{
"name": "fourth"
},
{
"name": "fifth"
},
{
"name": "sixth"
},
{
"name": "seventh"
}
]
},
{
"section_name": "DueDilligence",
"items": [
{
"name": "eighth"
}
]
}
]
*/

Returning an array of objects from other object

Hello am trying to extract some information from an object to create a graph but it returns undefined my object looks like
{
"concepts": [
{
"id_cpt": "1",
"fr_cpt": "Proche",
},
{
"id_cpt": "2",
"fr_cpt": "Loin",
}{
"id_cpt": "3",
"fr_cpt": "Here",
},...
],
"arcs": [
{
"idfrom":"1",
"idto":"2"
},
{
"idfrom":"3",
"idto":"2"
},....
]
}
I want to make an object looks like
const data = {
nodes: [{ id: 'Proche' }, { id: 'Loin' },{ id: 'Here' } ...],
links: [{ source: 'Proche', target: 'Loin' }, { source: 'Here', target: 'Loin' },...]
};
I want extract names not ids in links but the object arcs only have ids the code in es6 and thank you for helping me
You could loop through the concepts using for...of. Populate the nodes array and a map object. The map object has id_cpt as key and fr_cpt as value.
{
"1": "Proche",
"2": "Loin",
"3": "Here"
}
This object can be used to get the source and target value for links. Then loop through arcs and create links using map object
Here's a snippet:
const input = {"concepts":[{"id_cpt":"1","fr_cpt":"Proche",},{"id_cpt":"2","fr_cpt":"Loin",},{"id_cpt":"3","fr_cpt":"Here",},],"arcs":[{"idfrom":"1","idto":"2"},{"idfrom":"3","idto":"2"},]}
let nodes = [],
links = [],
map = {};
for (const { id_cpt, fr_cpt } of input.concepts) {
nodes.push({ id: fr_cpt });
map[id_cpt] = fr_cpt
}
for (const { idfrom, idto } of input.arcs) {
links.push({ source: map[idfrom], target: map[idto] }) // get the value using map
}
const output = { nodes, links }
console.log(output)

Insert array of objects to database

I have the following array containing objects, And there are arrays in the objects too.
let array = [
{
"data": {
"Game": {
"Game_number": [
"4",
"6",
"8"
],
"Game_name": [
"Name_1",
"Name_2",
"name_3"
]
},
"AA": {
"AA_count": [
"30"
],
"AA_name": [
"Umbrella"
]
},
}
}
]
Now i have to put them in database, Each have a column against.
But the issue is that the above data is not constant, So i cannot put them via their indexes. if the data is missing for a column than that's fine it will go empty
I tried via for each but that is inserting the last element of the array.
array.data.forEach((item) => {
const Games = Parse.Object.extend('Games');
const query = new Games();
item.data.Game.Game_number.forEach((number) => {
query.set('game_number', number);
}, this);
item.data.Game.Game_name.forEach((name) => {
query.set('game_name', name);
}, this);
query.save();
}, this);
What will be a flexible way to handle it ?

Categories