Javascript parse array of object strings into object of objects? - javascript

I am working with a 3rd party app that requires a specific structure of data for filtering a result set. I am struggling with figuring out how to parse this out as the end result isn't a conventional array of objects.
There is a function that takes in a list of IDs from an array and turns them into object strings:
Function:
// Input for articles is an array of IDs
// articles = ['kA10W000001UK2KSAW', 'kA1d0000000DB1CCAW', 'kA1d0000000DAsOCAW']
function createExclusion(articles){
let results = [];
articles.forEach(element => {
results.push(`"EqualsTo": {"Key": "sf_KnowledgeArticleId","Value": {"StringValue":"${element}"}}`)
})
return result;
}
Input Data:
let data = [
'"EqualsTo":{"Key":"sf_KnowledgeArticleId","Value":{"StringValue":"kA10W000001UK2KSAW"}},',
'"EqualsTo":{"Key":"sf_KnowledgeArticleId","Value":{"StringValue":"kA1d0000000DB1CCAW"}},',
'"EqualsTo":{"Key":"sf_KnowledgeArticleId","Value":{"StringValue":"kA1d0000000DAsOCAW"}}'
]
Desired End Result:
{
IndexId: 1,
PageSize: 2,
PageNumber: 3,
RequestedDocumentAttributes: ["_source_uri", "sf_ArticleNumber", "sf_KnowledgeArticleId"],
AttributeFilter: {
"NotFilter": {
"EqualsTo": {
"Key": "sf_KnowledgeArticleId",
"Value": {
"StringValue": "kA10W000001UK2KSAW"
}
},
"EqualsTo": {
"Key": "sf_KnowledgeArticleId",
"Value": {
"StringValue": "kA1d0000000DB1CCAW"
}
},
"EqualsTo": {
"Key": "sf_KnowledgeArticleId",
"Value": {
"StringValue": "kA1d0000000DAsOCAW"
}
},
},
SortingConfiguration: {
"DocumentAttributeKey": "_document_title",
"SortOrder": "ASC"
}
};
}
I am trying to re-create the AttributeFilter data in the end result by taking the array of strings and parsing it into the correct form.
Example:
I was trying to get it to work with JSON.parse(), but the data isn't in the correct format for that.
Between either adjusting the createExclusion function or easily parsing it in its existing form, how can I go about turning the list of object strings into just objects as seen in the desired end result?
function parse(data) {
return {
IndexId: 1,
PageSize: 2,
PageNumber: 3,
RequestedDocumentAttributes: ["_source_uri", "sf_ArticleNumber", "sf_KnowledgeArticleId"],
AttributeFilter: {
"NotFilter": ? // Parse data here
},
SortingConfiguration: {
"DocumentAttributeKey": "_document_title",
"SortOrder": "ASC"
}
};
}

First, you cannot have an object with duplicated keys in JSON:
{
"NotFilter": {
"EqualsTo": {
"Key": "sf_KnowledgeArticleId",
"Value": {
"StringValue": "kA10W000001UK2KSAW"
}
},
"EqualsTo": {
"Key": "sf_KnowledgeArticleId",
"Value": {
"StringValue": "kA1d0000000DB1CCAW"
}
},
"EqualsTo": {
"Key": "sf_KnowledgeArticleId",
"Value": {
"StringValue": "kA1d0000000DAsOCAW"
}
}
}
}
Your NotFilter value should be an array of objects.
Parsing JSON
Your JSON should be valid, prior to calling JSON.parse. Make sure you remove any trailing commas and wrap each line in curly-braces.
let data = [
'"EqualsTo":{"Key":"sf_KnowledgeArticleId","Value":{"StringValue":"kA10W000001UK2KSAW"}},',
'"EqualsTo":{"Key":"sf_KnowledgeArticleId","Value":{"StringValue":"kA1d0000000DB1CCAW"}},',
'"EqualsTo":{"Key":"sf_KnowledgeArticleId","Value":{"StringValue":"kA1d0000000DAsOCAW"}}'
]
const parsed = data.map(item => JSON.parse(`{${item.replace(/,$/, '')}}`));
console.log(parsed);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Related

how to get object that arepresent in object?

Actually I'm trying to get all the value of object1 and get true if Like object has some id that match with current user id
Array [
Object {
"id": "-MgFbI5wXjtjKln1Wkqe",
"like": Object {
"-MgpHytKWNplejaxtLLF": "-MgpHytKWNplejaxtLLF",
},
"likes_count": 7,
},
Object {
"id": "-MgpHytKWNplejaxtLLF",
"like": Object {
"-MgFbI5wXjtjKln1Wkqe": "aC9dL88GCAXdnGyefY1XDiXd7Iu1",
},
"likes_count": 0,
},
]
Here is my code, arr contains whole object that are given above
const us = arr.map((item) => {
return item.like;
});
const ik = us.includes(uid);
console.log("snap ", ik);
I want given below object that include like variable true if like object have user id otherwise it assign false
Array [
Object {
"id": "-MgFbI5wXjtjKln1Wkqe",
"like":false,
"likes_count": 7,
},
Object {
"id": "-MgpHytKWNplejaxtLLF",
"like":true,
"likes_count": 0,
},
]
const us =Array(); // us is the final table that you need
for(i=0;i<arr.length;i++){
us[i]= {
"id":arr[i].id,
"like": arr[i].like===uid?true:false,
"likes_count": arr[i].likes_count,
}
}
or this :
const us = Array();// us is the final table that you need
arr.forEach((element,index) => us[index] = {
"id":arr[index].id,
"like": arr[index].like===uid?true:false,
"likes_count": arr[index].likes_count,} );

How does one filter json after type?

So, I have a json which looks a little bit like this:
{
"data": {
"user": {
"edge_followed_by": {
"count": 22,
"page_info": {
"has_next_page": true,
"end_cursor": "Base64"
},
"edges": [
{
"node": {
"id": "id",
"username": "Username",
"full_name": "played",
"profile_pic_url": "URL"
}
}
]
}
}
}
}
And I want to filter out the username. How do I do that?
You could retrieve it with a map function there
const dataSample = {
"data": {
"user": {
"edge_followed_by": {
"count": 22,
"page_info": {
"has_next_page": true,
"end_cursor": "Base64"
},
"edges": [
{
"node": {
"id": "id",
"username": "Username",
"full_name": "played",
"profile_pic_url": "URL"
}
}
]
}
}
}
}
const getUsernames = data => {
return data.data.user.edge_followed_by.edges.map(e => e.node.username)
}
console.log(getUsernames(dataSample))
:)
This can be a little tricky to understand from the question first of all.
My interpretation of this is you want to extract a username
"Filtering" also could mean you want to remove something from a collection that passes a condition (or test) of some kind.
For example: Removing all even numbers from an array
let x = [1, 2, 4, 5, 6];
let filtered = x.filter(value => value % 2 === 0);
Now, I've looked at your json, and I think the best point of targeting this is by getting the "edges" property and running it through an inbuilt function like map; that could be used to get usernames. The edges is an array as well.
data.user.edge_followed_by.edges.map(userObject => userObject.username)
That would effectively remove all usernames from the edges if your tech stack of choice was javascript.
I got this info from a post like: https://coderin90.com/blog/2019/map-js

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 ?

node.js transform xml into json with xml2js

I am using the node.js package xml2js to transform xml into json.
Documentation is here: https://www.npmjs.com/package/xml2js
My problem is that attributes for those xml are not correctly transformed.
example XML with multiple events
<events><event id="E0-001-098932239-8"></event><event id="E0-001-105389601-2"></event><event id="E0-001-104342965-3"></event><event id="E0-001-104830349-3"></event><event id="E0-001-105374979-6"></event><event id="E0-001-105389620-7"></event><event id="E0-001-104247759-2"></event><event id="E0-001-104342949-5">
Result from JSON.stringify(result.search.events)
The event tag is only once in the generated JSON - My expectation is that it should have multiple tags event. So I assume the transformation process went wrong. I tried multiple options for the parser like ignoreAttrs, explicitArray or explicitChildren but without success.
[{
"event": [{
"$": {
"id": "E0-001-098932239-8"
},
]
}, {
"$": {
"id": "E0-001-105389601-2"
},
}, {
"$": {
"id": "E0-001-104342965-3"
},
}, {
"$": {
"id": "E0-001-104830349-3"
},
access JSON elements
After correct transformation I expect to simply access the JSON elements via event[1].$.id
but all tries are unsuccessful:
events.event --> undefined
events.event.$ --> undefined
events.$ --> undefined
My Question is now: how can i correctly transform the xml into JSON and access the elements correctly?
Javascript is starting from 0, you should get events[0].event[0].$.id
Also, you can try with another package (camaro) with simply and easily change the desired result.
Example:
const xml = '<events><event id="E0-001-098932239-8"></event><event id="E0-001-105389601-2"></event><event id="E0-001-104342965-3"></event><event id="E0-001-104830349-3"></event><event id="E0-001-105374979-6"></event><event id="E0-001-105389620-7"></event><event id="E0-001-104247759-2"></event><event id="E0-001-104342949-5"></event></events>'
const temp = {
events: ['/events/event', {
id: '#id'
}]
}
const transform = require('camaro')
const results = transform(xml, temp)
console.log(JSON.stringify(results, null, 2))
Results
{
"events": [
{
"id": "E0-001-098932239-8"
},
{
"id": "E0-001-105389601-2"
},
{
"id": "E0-001-104342965-3"
},
{
"id": "E0-001-104830349-3"
},
{
"id": "E0-001-105374979-6"
},
{
"id": "E0-001-105389620-7"
},
{
"id": "E0-001-104247759-2"
},
{
"id": "E0-001-104342949-5"
}
]
}

JSON formatting drill down issue

I am using dojo's arrayUtil.forEach to loop through my JSON object but when I get to data.graphs.metrics it does not continue because metrics is not an array. What options do I have?
xhr("/esp/files/eclwatch/ganglia.json", {
handleAs: "json"
}).then(function(data){
arrayUtil.forEach(data.graphs, function (item, idx) {
//never gets here.
});
});
}
//json file
{
"graphs": [
{
"name": "Bar",
"metrics":{
"metric": ["metric1, metric3"],
"metric": ["metric1", "metric4", "metric5"]
},
"time": ["Hour", "Month", "Week"]
}
]
}
Making it an array instead of giving it duplicate keys would make the most sense.
"metrics": [
["metric1, metric3"],
["metric1", "metric4", "metric5"]
],

Categories