JSON remove key value for particular key name - javascript

I have a JSON like the following, I am trying to remove "age" from it and rename "name" to "key" and "height" to "value". Can someone please suggest what would be the neatest way to achieve this.
{
"data": [
{
"name": "A",
"age": 8,
"height": 120
},
{
"name": "B",
"age": 18,
"height": 150
}
]
}

Here is how you do it using map as I mentioned.
map is exactly what you're looking for, it's a way to create a new array based on an existing array using whatever criteria you want.
var json = {
"data": [{
"name": "A",
"age": 8,
"height": 120
}, {
"name": "B",
"age": 18,
"height": 150
}]
};
json.data = json.data.map(function (d) {
return {
key: d.name,
value: d.height
};
});

Related

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);

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>
)

java script to parse an array from json

{
"took": 72,
"hits": {
"total": {
"value": 10000
}
},
"aggregations": {
"2": {
"buckets": [{
"key": "Perf",
"doc_count": 159874
}]
}
}
}
Could someone guide me to take the value of buckets
The built-in JSON should do the heavy lifting for you:
const str = '{ "took": 72, "hits": { "total": { "value": 10000 } }, "aggregations": { "2": { "buckets": [{ "key": "Perf", "doc_count": 159874 }] } } }';
const obj = JSON.parse(str);
the_arry = obj['aggregations']['2']['buckets'];
This should work:
var myrs = { "took": 72, "hits": { "total": { "value": 10000 } }, "aggregations": { "2": { "buckets": [{ "key": "Perf", "doc_count": 159874 }] } } };
for(var i in myrs["aggregations"]) {console.log(myrs["aggregations"][i]['buckets']);}
You can start by parsing the JSON string with var obj = JSON.parse(). It gives you an object representation of the string to work on. Log the object to the console to easily discover the structure console.log(obj); or use an online JSON viewer to do that.
Assuming the structure is fixed, the buckets array can be accessed by var buckets = obj.aggregations["2"].buckets. Notice the access of the property 2.

convert an array of objects to one object of objects

How to convert an array of objects to one object of objects. My function works but I don't want key name before each object.
myArray = [{
"name": "ann",
"y": 191,
"color": "red"
},{
"name": "mary",
"y": 11,
"color": "red"
},{
"name": "henry",
"y": 11,
"color": "red"
}]
let result = {};
for (let item of seriesTotal) {
result[item.name] = item;
delete item.name;
}
I'd like this
myObject = {{
"name": "ann",
"y": 191,
"color": "red"
},{
"name": "mary",
"y": 11,
"color": "red"
},{
"name": "henry",
"y": 11,
"color": "red"
}{
An object is a collection of properties, and a property is an association between a name (or key) and a value.
You can use the index as the key or property name. Use Object.assign to create a new object. Use map and spread syntax to loop thru the array.
let myArray = [{
"name": "ann",
"y": 191,
"color": "red"
}, {
"name": "mary",
"y": 11,
"color": "red"
}, {
"name": "henry",
"y": 11,
"color": "red"
}];
let result = Object.assign(...myArray.map((o,i) => ({[i]: o})));
console.log(result);
Doc: Objects
Since what you want is not valid JS object, you'll get an string in JS, so you could use .replace():
myArray = JSON.stringify(myArray).replace(/(\[)(.+)(\])/g,"{$2}");
console.log(myArray);
//{{"name":"ann","y":191,"color":"red"},{"name":"mary","y":11,"color":"red"},{"name":"henry","y":11,"color":"red"}}
But as I said before, that is not a JS object, it's just a string.

Filter and sort JSON formatted object?

Lets say I've got an object in JSON format (like below) and I want to sort it by UserID
oUserColors = { "users": [
{ "UserID": 31, "Color": "Red" },
{ "UserID": 30, "Color": "Red" },
{ "UserID": 32, "Color": "Green" },
{ "UserID": 30, "Color": "Green" },
{ "UserID": 32, "Color": "Red" }
] };
I can easily use the following function to do so.
objSortedUserColors = oUserColors.users.sort(function (a, b) {
return b.UserID - a.UserID; // sort oUserColors.users in descending order.
});
which would give me this...
objSortedUserColors = { "users": [
{ "UserID": 32, "Color": "Red" },
{ "UserID": 32, "Color": "Green" },
{ "UserID": 31, "Color": "Red" },
{ "UserID": 30, "Color": "Red" },
{ "UserID": 30, "Color": "Green" }
] };
But what if I want to also filter the object by color such that, if a user has both red and green as their color, the red gets removed and only the green remains. But if the user only has red as their color, it stays. Resulting in something like this...
objFilteredSortedUserColors = { "users": [
{ "UserID": 32, "Color": "Green" },
{ "UserID": 31, "Color": "Red" },
{ "UserID": 30, "Color": "Green" }
] };
I'm stuck. Any suggestions would be greatly appreciated!
As you know how to sort the array, I will just focus on the filter. You can use reduce for that and a helper object to maintain values keyed by UserUD. A Map would also work, but plain objects have an advantage of producing values in the order of increasing keys when they are non-negative integers.
const oUserColors = { "users": [{ "UserID": 31, "Color": "Red" },{ "UserID": 30, "Color": "Red" },{ "UserID": 32, "Color": "Green" },{ "UserID": 30, "Color": "Green" },{ "UserID": 32, "Color": "Red" }]};
const result = Object.values(oUserColors.users.reduce( (acc, obj) => {
const prev = acc[obj.UserID];
if (!prev || prev.Color === 'Red') {
acc[obj.UserID] = obj;
}
return acc;
}, {}));
console.log(result);
The idea is to build an object (acc) with only the values of interest, keyed by UserID. If you find that during this collection there is no value yet for a UserID, you add it. If there is a value, and it has colour Red, then it is safe to replace it with the current object.
With Object.values() you convert that object back to an Array.
As it happens that JavaScript in all common browsers will produce the values in order of numerical key order (if non-negative integers), the output will be sorted.

Categories

Resources