Searching and editing nested JSON elements - javascript

Basically I want to be able, in Javascript (JQuery optionally), to search into a JSON with nested elements for a particular element and edit it.
Ex. search for "components" with id 110 and change the name to "video card".
Notice the following JSON is just an example. I am wondering if javascript libraries or good tricks exist to do such a thing, I don't think traversing the whole json or writing my own methods is the best solution.
{
"computers": [
{
"id": 10,
"components": [
{
"id": 56,
"name": "processor"
},
{
"id": 24,
"name": "ram"
}
]
},
{
"id": 11,
"components": [
{
"id": 110,
"name": "graphic card"
},
{
"id": 322,
"name": "motherboard"
}
]
}
]
}

You could try linq.js.

You can use this javascript lib, DefiantJS (http://defiantjs.com), with which you can filter matches using XPath on JSON structures. To put it in JS code:
var data = {
"computers": [
{
"id": 10,
"components": [
{ "id": 56, "name": "processor" },
{ "id": 24, "name": "ram" }
]
},
{
"id": 11,
"components": [
{ "id": 110, "name": "graphic card" },
{ "id": 322, "name": "motherboard" }
]
}
]
},
res = JSON.search( data, '//components[id=110]' );
res[0].name = 'video card';
Here is a working fiddle;
http://jsfiddle.net/g8fZw/
DefiantJS extends the global object JSON with the method "search" and returns an array with matches (empty array if no matches were found). You can try out the lib and XPath queries using the XPath Evaluator here:
http://www.defiantjs.com/#xpath_evaluator

Related

Nesting sequelize.query results in a array of objects for INNER JOIN results

I'm trying to nest the results of a query with sequelize, I'm passing the raw query string in the sequelize.query function and organizing the results with the dotted notation with the option nest set to true. It is working and returning the results as intended, but it is not nesting the results in an array format, leaving the "root" object duplicated.
const result = await db.sequelize.query(s.toString(),
{
nest: true,
type: db.sequelize.QueryTypes.SELECT,
raw: true,
})
return result
This is the query generated by sequelize:
SELECT [UserCertifications].id AS [UserCertifications.id],[UserCertifications].campaign_id AS [UserCertifications.campaign_id],[UserCertifications].user_id AS [UserCertifications.user_id],[UserCertifications].certification AS [UserCertifications.certification],[Users].name AS [UserCertifications.Items.Users.name],[Items].title AS [UserCertifications.Items.title] FROM [UserCertifications] INNER JOIN [Items] ON (UserCertifications.item_id = Items.id) INNER JOIN [Users_Items] ON (Users_Items.item_id = Items.id) INNER JOIN [Users] ON (Users_Items.user_id = [Users].id) WHERE (campaign_id = 78)
It returns like this:
[
{
"UserCertifications": {
"id": 324,
"campaign_id": 78,
"user_id": 1,
"certification": null,
"Items": {
"Users": {
"name": "Admin"
},
"title": "Item 1"
}
}
},
{
"UserCertifications": {
"id": 324,
"campaign_id": 78,
"user_id": 1,
"certification": null,
"Items": {
"Users": {
"name": "Services"
},
"title": "Item 1"
}
}
},
{
"UserCertifications": {
"id": 324,
"campaign_id": 78,
"user_id": 1,
"certification": null,
"Items": {
"Users": {
"name": "Lucas"
},
"title": "Item 1"
}
}
},
{
"UserCertifications": {
"id": 324,
"campaign_id": 78,
"user_id": 1,
"certification": null,
"Items": {
"Users": {
"name": "Wally"
},
"title": "Item 1"
}
}
},
{
"UserCertifications": {
"id": 325,
"campaign_id": 78,
"user_id": 1,
"certification": null,
"Items": {
"Users": {
"name": "Admin"
},
"title": "Item 1"
}
}
},
...this is not the entire result, it is too big, but you can get the idea of what im alking about through this example.
The problem is, the result is correct, with "Items" and "Users" nested as intended, but i would like the result to be nested in a way that all the UserCertifications with "id: 324" are a single object with a single "Item" ("Item 1") and the users as an Array of users. Is there a way to nest the results like this using the dotted notation with Sequelize?
Aditional context: I'm passing the alias of the table names "Items" and "Users" like this to get that result, "UserCertifications.Items.title" and "UserCertifications.Items.Users.name", respectively
Disclaimer: It needs to be a raw query because I am building a query string from scratch using a "query builder", so i can't use the "Include" notation from sequelize.

Remove the first bracket from nested array

I have an array as follow:
let data =[
[
{
"Id": "110d611c-54e4-4593-a835-def0f34ed882",
"duration": 30,
"name": "burger",
"price": 10,
}
],
[
{
"Id": "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
"duration": 10,
"name": "Cake",
"price": 5,
}
]
]
I am trying to remove the first bracket to be like this:
let data =
[
{
"Id": "110d611c-54e4-4593-a835-def0f34ed882",
"duration": 30,
"name": "burger",
"price": 10,
}
],
[
{
"Id": "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
"duration": 10,
"name": "Cake",
"price": 5,
}
]
I have trying many solutions, the most common one i have tried is using this way:
let newData = data[0]
but the result always giving me the first nested array something like this:
[
{
"Id": "110d611c-54e4-4593-a835-def0f34ed882",
"duration": 30,
"name": "burger",
"price": 10
}
]
I tried to convert it to string using JSON.stringify() then remove the bracket by doing
JSON.stringify(data).substring(1, JSON.stringify(data).length - 1);
But then when i parse it i get this error:
SyntaxError: JSON Parse error: Unable to parse JSON string
I am really stuck on what the best way to accomplish it.
thanks in advance.
You want the first element of each nested array, not the first element of the outer array. So use map().
let data = [
[{
"Id": "110d611c-54e4-4593-a835-def0f34ed882",
"duration": 30,
"name": "burger",
"price": 10,
}],
[{
"Id": "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
"duration": 10,
"name": "Cake",
"price": 5,
}]
];
let newData = data.map(el => el[0]);
console.log(newData);
Removing the external bracket will result in an invalid javascript object.
To obtain a single array with all the objects you can use flatMap
data.flatMap(x => x)
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap
The result that you want is not valid, instead you can get array of object using flat as:
data.flat()
let data = [
[
{
Id: "110d611c-54e4-4593-a835-def0f34ed882",
duration: 30,
name: "burger",
price: 10,
},
],
[
{
Id: "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
duration: 10,
name: "Cake",
price: 5,
},
],
];
const result = data.flat();
console.log(result);

rename all key's objects JS

I want to rename some of my key's object but with a map it sounds quite difficult (I'm a newbie) here is my array :
"platforms": [
{
"id": 6,
"name": "PC (Microsoft Windows)"
},
{
"id": 11,
"name": "Xbox"
},
{
"id": 14,
"name": "Mac"
},
{
"id": 48,
"name": "PlayStation 4"
},
{
"id": 130,
"name": "Nintendo Switch"
}
],
And this is what i want it to be :
"platforms": [
{
"id": 6,
"name": "PC"
},
{
"id": 11,
"name": "Xbox"
},
{
"id": 14,
"name": "Mac"
},
{
"id": 48,
"name": "PS4"
},
{
"id": 130,
"name": "Switch"
}
],
And here is my code :
const renderedResults = results.map((result, index) => {
const platformSliced = result.platforms.slice(0,3);
return (
{platformSliced.map((platform) =>
<span className="main-game-card-platform">
{platform.name}.replace('PC (Windows Microsoft)', 'PC')
</span>
)}
);
});
It doesn't work maybe I should do a condition, but how can I write it ? Thank you
Create an object where the keys are the strings you want changed, and the values the strings that should replace the old string.
With .map() method, return a new object for each item, where the id is unchanged. The name property should look first in the new "rewrites" object if the value of name exists as a key in the object. If it does, then the value should be used, otherwise there is no rewrite and the old name should be used.
const rewrites = {
"PC (Microsoft Windows)": 'PC',
"PlayStation 4": 'PS4',
"Nintendo Switch": 'Switch'
};
const platforms = [
{
"id": 6,
"name": "PC (Microsoft Windows)"
},
{
"id": 11,
"name": "Xbox"
},
{
"id": 14,
"name": "Mac"
},
{
"id": 48,
"name": "PlayStation 4"
},
{
"id": 130,
"name": "Nintendo Switch"
}
];
const rewrittenPlatforms = platforms.map(({ id, name }) => ({
id,
name: rewrites[name] ?? name // Use rewritten name, if present, otherwise use old name.
}));
console.log(rewrittenPlatforms);

how to show json array by hierarchical sub cats in react js

I receive through api one json with this structure.
And I want to display the objects as follows.
But I do not know in map array by react js how to get in objects and sub-objects.
json code:
[
{
"term_id": 15,
"name": "Uncategorized",
"children": [
]
},
{
"term_id": 21,
"name": "Clothing",
"children": [
{
"term_id": 24,
"name": "Accessories",
"children": [
{
"term_id": 24,
"name": "Accessories",
"children": [
]
},
{
"term_id": 23,
"name": "Hoodies",
"children": [
]
},
{
"term_id": 22,
"name": "Tshirts",
"children": [
]
}
]
},
{
"term_id": 23,
"name": "Hoodies",
"children": [
]
},
{
"term_id": 22,
"name": "Tshirts",
"children": [
]
}
]
},
{
"term_id": 26,
"name": "Decor",
"children": [
]
},
{
"term_id": 25,
"name": "Music",
"children": [
]
}
]
And I want to show it this way:
Uncategorized
Clothing
-Accessories
--Bike
--Engine
---Bench
--Airplane
Hoodies
Tshirts
I just answered a similar question to this one. So I'll just leave the link and copy paste the answer as well:
https://stackoverflow.com/a/66838788/15160090
Just let me know if you have any questions about this and I'll elaborate further on what you'd need to do.
For this kind of operation I suggest using Lodash. It's a very cool library with tons of useful methods to help you on your project.
https://lodash.com/docs/
Lodash has a groupBy method, easy to use, and I believe it does what you are looking for. So in your case, you would have something like this:
const categories = _.groupBy(data, "name");
You basically pass the array you want to group, along with the key name you want to group by.
Hope this was helpful.
You can use recursive function to solve your issue
function recursive(arrayJson, level=0)
{
let childrenComp = null
If(arrayJson.children)
childrenComp = recursive(arrayJson.children, level++)
return <>
<Text>{level > 0 && “-“.repeat(level)}arrayJson.name</Text>
{childrenComp}
</>
}
render(
const components = arrayJson && this.recursive(arrayJson)
return <View>{components}</View>
)

Remove special characters from a specific JSON object in JSON payload

I have a large JSON payload and I want to format, the specific object of the payload using JS.
I want flightdetails array object to edit and remove the special characters from it. How can I achieve this?
I have been working on this using XSLT for the past 2 days, and I went nowhere hence I decided to remove it using JS.
Example of the array(there can be more than 30 records inside the flightdetails)
"flightdetails": [
{
"id": XF-2092,
"trips": 2,
"categories": {
"flights": [
"\"return\",\"oneway\""
]
},
"id": XF-2093,
"trips": 1,
"categories": {
"flights": [
"\"return\""
]
}
}
]
Expected Output
"flightdetails": [
{
"id": XF-2092,
"trips": 2,
"categories": {
"flights": [
"return","oneway"
]
},
"id": XF-2093,
"trips": 1,
"categories": {
"flights": [
"return"
]
}
}
]
The flightdetails object inside the //destinations/flightdetails path

Categories

Resources