Remove the first bracket from nested array - javascript

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

Related

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

copying an array of object and ordering some items

I have an array of object and I want to copy that array of object to another array while modifying some items, like copying id only by ascending order and copying only the value of trophies of basketball to trophies. How to do it?
const item = [{
"id": 33,
"name": "John"
"trophies": {
"basketball" : 2,
"baseball" : 5
},
"profile": "profile/212"
}
{
"id": 12,
"name": "Michael"
"trophies": {
"basketball" : 6,
"baseball" : 7
},
"profile": "profile/341"
}
]
I want the above array of object after copying to look something like
const item2 = [{
"id": 12,
"name": "Michael"
"trophies": 6,
"profile": "http://collegeprofile.com/profile/341"
},
{
"id": 33,
"name": "John"
"trophies": 2,
"profile": "http://collegeprofile.com/profile/212"
}
]
You can sort by id ascending order using Array.prototype.sort
And map basketball value to trophies using Array.prototype.map.
const item = [{
"id": 33,
"name": "John",
"trophies": {
"basketball": 2,
"baseball": 5
},
"profile": "profile/212"
}, {
"id": 12,
"name": "Michael",
"trophies": {
"basketball": 6,
"baseball": 7
},
"profile": "profile/341"
}];
const output = item.sort((a, b) => (a.id - b.id)).map((item) => ({
...item,
trophies: item.trophies.basketball,
profile: "http://collegeprofile.com/" + item.profile
}));
console.log(output);

Group object values by date

I'm trying to make an upcoming event on react native, I have this object
const calendatData = [
{
"data": [
{
"id": 25,
"title": "Spotify",
"name": "Family",
"service_id": 1,
"repetition": "Monthly",
"price": "79000",
"upcoming_date": [
"2020-08-07T13:35:44.606Z"
]
},
{
"id": 26,
"title": "Netflix",
"name": "Mobile",
"service_id": 2,
"repetition": "Monthly",
"price": "49000",
"upcoming_date": [
"2020-08-18T13:35:44.600Z",
"2020-08-07T13:35:44.606Z"
]
},
{
"id": 27,
"title": "iTunes",
"name": "Weekly Special",
"service_id": 3,
"repetition": "Weekly",
"price": "22000",
"upcoming_date": [
"2020-08-07T13:35:44.606Z",
"2020-08-14T13:35:44.606Z",
"2020-08-21T13:35:44.606Z",
"2020-08-28T13:35:44.606Z"
]
}
],
"status": "success"
}
]
what I've been trying to do is to extract that object based on the upcoming_date.
the result that I need is like this
upcomingData = [
{
date: '2020-08-07',
title: [
'Spotify',
'Netflix',
'iTunes'
]
},
{
date: '2020-08-18',
title: ['Netflix']
},
{
date: '2020-08-14',
title: ['iTuunes']
},
{
date: '2020-08-21',
title: ['iTuunes']
},
{
date: '2020-08-28',
title: ['iTuunes']
}
]
On the same date, if there are multiple titles, it should be grouped under the same date in the object.
instead what I got was this object
upcomingData = [
{
title: [
"Spotify",
"Netflix",
"iTunes",
],
date : [
"2020-08-29",
"2020-08-07",
"2020-08-18",
"2020-08-07",
"2020-08-07",
"2020-08-14",
"2020-08-21",
"2020-08-28",
]
}
]
I am new to this, and I'm aware that this is mostly about javascript knowledge, any help would be appreciated.
thanks
The ideas are:
First, iterate your object by Array.prototype.map() and set a unique map key from the converted date.
Then push the title to every map's key.
Actually your final map(here is myMap) will be your expected upcomingData. To output as your expected object, you can make it in your own way.
const calendarData = [{ "data": [{ "id": 25, "title": "Spotify", "name": "Family", "service_id": 1, "repetition": "Monthly", "price": "79000", "upcoming_date": ["2020-08-07T13:35:44.606Z"] }, { "id": 26, "title": "Netflix", "name": "Mobile", "service_id": 2, "repetition": "Monthly", "price": "49000", "upcoming_date": ["2020-08-18T13:35:44.600Z", "2020-08-07T13:35:44.606Z"] }, { "id": 27, "title": "iTunes", "name": "Weekly Special", "service_id": 3, "repetition": "Weekly", "price": "22000", "upcoming_date": ["2020-08-07T13:35:44.606Z", "2020-08-14T13:35:44.606Z", "2020-08-21T13:35:44.606Z", "2020-08-28T13:35:44.606Z"] }], "status": "success" }];
var myMap = new Map();
calendarData[0].data.map(element => {
var dates = [];
element.upcoming_date.map(date => {
var upcoming_date = date.slice(0,10);
if (!myMap.get(upcoming_date)) {
myMap.set(upcoming_date, []);
}
dates.push(upcoming_date);
});
var len = dates.length;
for (let i = 0; i < len; i++) {
myMap.get(dates[i]).push(element.title);
}
});
var upcomingData = [];
for (const entry of myMap.entries()) {
var obj = {};
obj["date"] = entry[0];
obj["title"] = entry[1];
upcomingData.push(obj);
}
console.log(upcomingData);
You may
traverse your source array with Array.prototype.reduce() building up the Map where trimmed portion of your date string is used as a key and the object of desired format as a value
extract Map values, using Map.prototype.values() into resulting array
Following is a quick live demo:
const src = [{"data":[{"id":25,"title":"Spotify","name":"Family","service_id":1,"repetition":"Monthly","price":"79000","upcoming_date":["2020-08-07T13:35:44.606Z"]},{"id":26,"title":"Netflix","name":"Mobile","service_id":2,"repetition":"Monthly","price":"49000","upcoming_date":["2020-08-18T13:35:44.600Z","2020-08-07T13:35:44.606Z"]},{"id":27,"title":"iTunes","name":"Weekly Special","service_id":3,"repetition":"Weekly","price":"22000","upcoming_date":["2020-08-07T13:35:44.606Z","2020-08-14T13:35:44.606Z","2020-08-21T13:35:44.606Z","2020-08-28T13:35:44.606Z"]}],"status":"success"}],
result = [...src[0].data
.reduce((r,{upcoming_date, title}) => (
upcoming_date.forEach((s,_,__,date=s.slice(0,10)) =>
r.set(
date,
{date, title: [...(r.get(date)?.title||[]), title]}
)),r),
new Map())
.values()
]
console.log(result)
.as-console-wrapper{min-height:100%;}

Accessing nest elements by their keys with d3.js

So I have the following nest:
var myNest = [
{"key":"1","values":[...]},
{"key":"2","values":[...]},
{"key":"3","values":[...]},
]
How can I access these elements using their keys?
I know I can access them by their index
myNext[0] //return elements with key=="1"
myNest[1] //return elements with key=="2"
But what I would like to do is:
myNest["1"] //return elements with key=="1"
myNest["2"] //return elements with key=="2"
Thanks
Use map() instead of entries() when building your nest. You probably did something similar to this:
var products = [{
"id": 1,
"name": "Cat Hat",
"price": 49
}, {
"id": 2,
"name": "Unicorn Boots",
"price": 139
}, {
"id": 3,
"name": "Pink Woolly Jumper",
"price": 34
}];
var productsById = d3.nest()
.key(function(p) {
return p.id;
})
.entries(products);
console.log(productsById)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
If instead you use map():
var products = [{
"id": 1,
"name": "Cat Hat",
"price": 49
}, {
"id": 2,
"name": "Unicorn Boots",
"price": 139
}, {
"id": 3,
"name": "Pink Woolly Jumper",
"price": 34
}];
var productsById = d3.nest()
.key(function(p) {
return p.id;
})
.map(products);
console.log(productsById)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
You get a map where you can access objects by their key directly, e.g. with productsById["2"] in this example.
You could us a hash table, where the key of your object is the key for the object itselft.
For ES6 I suggest to use a Map:
var myNest = [{ key: "1", values: [1, 4] }, { key: "2", values: [2, 5] }, { key: "3", values: [3, 6] }],
hash = Object.create(null);
myNest.forEach(function (a) {
hash[a.key] = a;
});
console.log(hash['2']);

Searching and editing nested JSON elements

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

Categories

Resources