"items": {
"hotdrinks": [
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 20,
"name": "Tea",
"img": "../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 25,
"name": "Coffee",
"img": "../assets/img/Hot Drinks/2_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 50,
"name": "Hot Milk",
"img": "../assets/img/Hot Drinks/3_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 70,
"name": "Horlicks",
"img": "../assets/img/Hot Drinks/4_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 80,
"name": "Badam Milk",
"img": "../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
],
}
json i want to achieve using javascript. im just new to handling arrays and objects. thanksfound the answer given by Jeeva which works perfectly
future answers are welcome since we can know diffferent methods to achieve the same json object
dataArray = [
{title:"Hotdrinks",
content: [{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 20,
"name": "Tea",
"img": "../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 80,
"name": "Badam Milk",
"img": "../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
]}
You can use like this. This can be achieved by iterating the object.
const data = {
"items":{
"hotdrinks":[
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":20,
"name":"Tea",
"img":"../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":25,
"name":"Coffee",
"img":"../assets/img/Hot Drinks/2_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":50,
"name":"Hot Milk",
"img":"../assets/img/Hot Drinks/3_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":70,
"name":"Horlicks",
"img":"../assets/img/Hot Drinks/4_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":80,
"name":"Badam Milk",
"img":"../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
]
}
}
var dataArray = []
for(k in data.items){
var dataObj = {}
dataObj.title = k
dataObj.content = data.items[k] //You can also access the object values by using bracket ([]) notation
dataArray.push(dataObj)
}
console.log(JSON.stringify(dataArray))
The above expected output json is not valid. We can achieve the following.
[{"title":"Hotdrinks"}, {"content": [
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":20,
"name":"Tea",
"img":"../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":25,
"name":"Coffee",
"img":"../assets/img/Hot Drinks/2_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":50,
"name":"Hot Milk",
"img":"../assets/img/Hot Drinks/3_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":70,
"name":"Horlicks",
"img":"../assets/img/Hot Drinks/4_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":80,
"name":"Badam Milk",
"img":"../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
]}]
If you are okay with this then i'll give you the sample code for the same.
Related
I have a json file.
[
{
"line": 1,
"elements": [
{
"start_timestamp": "2022-10-17T20:07:41.706Z",
"steps": [
{
"result": {
"duration": 12216552000,
"status": "passed"
},
"line": 5,
"name": "m0e",
"match": {
"location": "seleniumgluecode.book.user_is_on_homepagee()"
},
"keyword": "Given "
},
{
"result": {
"duration": 2074982200,
"status": "passed"
},
"line": 6,
"name": "m1e1",
"match": {
"location": "seleniumgluecode.book.user_enters_Usernamee()"
},
"keyword": "When "
}
],
"tags": [
{
"name": "#Smokee"
}
]
},
{
"start_timestamp": "2022-10-17T20:08:12.284Z",
"steps": [
{
"result": {
"duration": 12090584100,
"status": "passed"
},
"line": 12,
"name": "m0e2",
"match": {
"location": "seleniumgluecode.book2.user_is_on_homepageee()"
},
"keyword": "Given "
}
],
"tags": [
{
"name": "#Smokee"
}
]
}
],
"name": "Login Featuree",
"description": " Verify if user is able to Login in to the sitee",
"id": "login-featuree",
"keyword": "Feature",
"uri": "file:src/test/java/features/tribe/squad1/kitab.feature",
"tags": []
},
{
"line": 1,
"elements": [
{
"start_timestamp": "2022-10-17T20:08:34.480Z",
"steps": [
{
"result": {
"duration": 11366098500,
"status": "passed"
},
"line": 5,
"name": "m0e",
"match": {
"location": "seleniumgluecode.book.user_is_on_homepagee()"
},
"keyword": "Given "
}
],
"tags": [
{
"name": "#Smokee"
}
]
}
],
"name": "Login Featureefghfgh",
"description": " Verify if user is able to Login in to the sitee",
"id": "login-featureefghfgh",
"keyword": "Feature",
"uri": "file:src/test/java/features/tribe1/squad2/kitab2.feature",
"tags": []
},
{
"line": 19,
"elements": [
{
"start_timestamp": "2022-10-17T20:09:40.836Z",
"steps": [
{
"result": {
"duration": 12761711100,
"status": "passed"
},
"line": 23,
"name": "m0e",
"match": {
"location": "seleniumgluecode.book.user_is_on_homepagee()"
},
"keyword": "Given "
}
],
"tags": [
{
"name": "#Smokee"
}
]
}
],
"name": "X Feature",
"description": " Verify if user is able to Login in to the sitee",
"id": "login-featuree",
"keyword": "Feature",
"uri": "file:src/test/java/features/tribe2/test.feature",
"tags": []
}
]
I am getting url addresses in this array
document.addEventListener("DOMContentLoaded", () => {
var i = report.length;
var array = [];
for(x = 0; x < i; x++){
array.push(report[x].uri.split("/"));
}
console.log(array2);
});
This return me :
0:
(7) ['file:src', 'test', 'java', 'features', 'tribe1', 'squad1', 'kitab.feature']
1:
(7) ['file:src', 'test', 'java', 'features', 'tribe1', 'squad2', 'kitab2.feature']
2:
(6) ['file:src', 'test', 'java', 'features', 'tribe2, kitab3.feature']
I don't need file:src, test, java, features. Deleting them in 3 arrays and getting a unique array like this:
0:
(3) ['tribe1', 'squad1', 'kitab.feature']
1:
(3) ['tribe1', 'squad2', 'kitab2.feature']
2:
(2) ['tribe2, kitab3.feature']
Finally, if there are 2 elements before the .feature, I need to create a new array by considering 1 as squad and 2 as tribe. Like this:
Diagram
[tribe1
squad1
elem
1
2
name
url
squad2
elem
1
2
name
url
tribe2
elem
1
2
name
url
]
How can I do that?. Thank you.
You should try destructing the array. An example is shown below:
[a,b,c,d, ...rest] = ['file:src', 'test', 'java', 'features', 'tribe1', 'squad1', 'kitab.feature']
console.log(rest);
You can transform or create a new array based on input array with this simple logic with the help of Array.map() along with String.split() and Array.splice() method.
Live Demo :
const arr = [
{
"line": 1,
"uri": "file:src/test/java/features/tribe/squad1/kitab.feature"
},
{
"line": 1,
"uri": "file:src/test/java/features/tribe1/squad2/kitab2.feature"
},
{
"line": 19,
"uri": "file:src/test/java/features/tribe2/test.feature"
}
];
const res = arr.map(({ uri}) => uri.split('/').splice(4));
console.log(res);
I have a JavaScript array with the following format:
[
{
"header": true,
"id": "0",
"name": "dairy",
},
{
"category": "dairy",
"header": false,
"id": "-LSlje6ESGALGpckMhb7",
"name": "milk",
},
{
"category": "dairy",
"header": false,
"id": "-LSm9EpFg5DhW036aUle",
"name": "cheese",
},
{
"header": true,
"id": "3",
"name": "dessert",
},
{
"category": "dessert",
"header": false,
"id": "-LSm9MLZkrnvtPySw5U6",
"name": "cake",
},
{
"category": "dessert",
"header": false,
"id": "-LSmAQ0rdDLrpz0TSPuD",
"name": "pie",
},
{
"header": true,
"id": "6",
"name": "fruit",
},
{
"category": "fruit",
"header": false,
"id": "-LSlazVIGAKLakxAIa8G",
"name": "apple",
},
{
"category": "fruit",
"header": false,
"id": "-LSlb5GH6xZz-DpNVS22",
"name": "pear",
},
{
"category": "fruit",
"header": false,
"id": "-LSwWJldY1nxQrotyv-V",
"name": "strawberry",
},
{
"header": true,
"id": "10",
"name": "meat",
},
{
"category": "meat",
"header": false,
"id": "-LSljXQzfXthJbOA54Ah",
"name": "fish",
},
{
"category": "meat",
"header": false,
"id": "-LSmA2-R9pOY8abAUyST",
"name": "steak",
},
{
"category": "meat",
"header": false,
"id": "-LSmAJ4J4gIfVQ8sgPDa",
"name": "pork",
},
]
What I am trying to do, is map through this array, and transform it to the following format:
[
{
title: nameOfFirstHeader,
data: items.slice(indexOfFirstHeader, indexOfSecondHeader),
},
{
title: nameOfSecondHeader,
data: items.slice(indexOfSecondHeader, indexOfThirdHeader),
},
{
title: nameOfThirdHeader,
data: items.slice(indexOfThirdHeader, indexOfFourthHeader),
},...and so on
]
So basically there will be an object section for each 'header' that is found in the original array. Each object section data property will contain the items found between the first header and the second header, and so on, until there are no more headers. I really can't wrap my head around how I can do this. Here is a reference to the the module I am using: https://github.com/saleel/react-native-super-grid#sectiongrid-example
Thanks!
I think this may be what you're trying to accomplish...
var grouped = items.reduce((acc,obj)=>{
let {header, name} = obj;
if (header) return [...acc, { title:name, data:[] }] // either first matching header or new match. Add fresh 'header' object
if (!acc.length) return acc; //not header and none have passed. Do nothing
let allButLast = acc.slice(0, acc.length-1),
lastElem = acc[acc.length-1]; // not a header, but there is an existing match. Add it to last match's data array
return [
...allButLast,
{
...lastElem,
data:[...lastElem.data, obj]
}
]
},[])
but it seems unreliable to trust the order of an array for this purpose. It would probably be more reliable to match by isHeader.name === notHeader.category to be less presumptive about the order of data you're iterating over. Like this...
var grouped = items.reduce((acc,obj)=>{
let {header, name, category} = obj;
if (header) return [...acc, { title:name, data:[] }];
if (!acc.length) return acc;
return acc.map((elem)=>{
if (elem.title !== category) return elem;
return {
...elem,
data: [ ...elem.data, obj]
};
})
},[])
I think you can probably do something like
const data = [];
let activeIndexForData = -1;
for(let i = 0; i < dataToSort.length -1; i++) {
if(dataToSort[i].header) {
activeIndexForData++;
}
if(data.length < activeIndexForData - 1) {
data.push({ title: dataToSort[i].name, data# []})
}
else {
data[activeIndexForData].data.push({ title: dataToSort[i].name, data: [])
}
}
I'm querying data, where the structure is something like this.
I have two models, FoodDrinks and Cuisines. They have many to many relation.
Now on the following query
{
"filter": {
"include": "cuisines"
}
}
I am getting the following results.
[
{
"id": 1,
"name": "Biryani",
"cuisines": [
{
"id": 1,
"name": "Mughlai"
},
{
"id": 2,
"name": "North Indian"
},
{
"id": 3,
"name": "Afghani"
}
]
},
{
"id": 2,
"name": "Chhole Bhature",
"cuisines": [
{
"id": 2,
"name": "North Indian"
}
]
},
{
"id": 3,
"name": "Amritsari Naan",
"cuisines": [
{
"id": 2,
"name": "North Indian"
},
{
"id": 6,
"name": "Punjabi"
},
]
}
]
Now I want only those food drinks which have cuisines from the following array.
let cuisinesIDs = ["1", "2"]
What will the following query for that?
I guess something like the below should work:
{
"filter": {
"include": "cuisines"
},
"where": {
"cuisines.id": {
"inq": cuisinesIDs
}
}
}
It might be the same answer as #Behrooz, but I would try:
{
"filter": {
"include": {
relation: 'cuisines',
scope: {
where: {
id: {inq: cuisinesIDs}
}
}
}
}
}
So I'm having an issue - I'm getting some data from our internal API at work, but it's not in the correct format I need to do what I have to do, so I have to make some transformations.
For this, I decided to use Lodash, however I'm stuck now.
Basically, I'm working with orders, but some of the products are addons to a parent product. I've managed so far to separate these two types of products, but I don't know how I should go about adding an "addons" array as a child to the parent product with matching ID.
Here's a basic stripped example of the output I'd like:
{
"order": {
"orderLines: [
{
"orderId": "foo",
"addons" [
{
...
}
]
},
{
...
}
]
}
}
And here's my current code:
// TODO:
// Match addons to products based on "connectedTo" => "id", then add matching addons as a new array on parent object
// Base data
const data = {
"order": {
"shopOrderId": "19LQ89H",
"createDate": "2017-10-24T13:09:22.325Z",
"orderLines": [
{
"orderId": "19LQ89H",
"product": {
"productName": "Paintball",
},
"id": "59ef3b8036e16f1c84787c1f",
"stringId": "59ef3b8036e16f1c84787c1f"
},
{
"orderId": "19LQ89H",
"product": {
"productName": "Ølsmagning",
},
"id": "59ef3b8036e16f1c84787c20",
"stringId": "59ef3b8036e16f1c84787c20"
},
{
"orderId": "19LQ89H",
"product": {
"productName": "CD-indspilning",
},
"id": "59ef3b8136e16f1c84787c21",
"stringId": "59ef3b8136e16f1c84787c21"
},
{
"orderId": "19LQ89H",
"product": {
"productName": "Julefrokost",
},
"id": "59ef3b8236e16f1c84787c22",
"stringId": "59ef3b8236e16f1c84787c22"
},
{
"orderId": "19LQ89H",
"product": {
"productName": "Hummer Limousine",
},
"id": "59ef3b8236e16f1c84787c23",
"stringId": "59ef3b8236e16f1c84787c23"
},
{
"orderId": "19LQ89H",
"connectedTo": "59ef3b8236e16f1c84787c23",
"product": {
"productName": "Ekstra kørsel 400",
},
"id": "59ef3b8236e16f1c84787c24",
"stringId": "59ef3b8236e16f1c84787c24"
},
{
"orderId": "19LQ89H",
"connectedTo": "59ef3b8236e16f1c84787c23",
"product": {
"productName": "Drikkevarer",
},
"id": "59ef3b8236e16f1c84787c25",
"stringId": "59ef3b8236e16f1c84787c25"
},
{
"orderId": "19LQ89H",
"connectedTo": "59ef3b8236e16f1c84787c23",
"product": {
"productName": "Drikkevarer",
},
"id": "59ef3b8236e16f1c84787c26",
"stringId": "59ef3b8236e16f1c84787c26"
},
{
"orderId": "19LQ89H",
"connectedTo": "59ef3b8236e16f1c84787c22",
"product": {
"productName": "Snaps ad libitum",
},
"id": "59ef3b8236e16f1c84787c27",
"stringId": "59ef3b8236e16f1c84787c27"
}
],
"travelTimes": [
{
"id": "59ef3b8036e16f1c84787c1f-59ef3b8036e16f1c84787c20",
"partyPlanFromEventId": "59ef3b8036e16f1c84787c1f",
"partyPlanToEventId": "59ef3b8036e16f1c84787c20",
"start": "2017-11-15T17:02:59",
"end": "2017-11-15T17:30:00",
"travelTimeString": "27 min.",
"travelTimeMinutes": 28,
"exceedsAvailableTime": false
},
{
"id": "59ef3b8036e16f1c84787c20-59ef3b8136e16f1c84787c21",
"partyPlanFromEventId": "59ef3b8036e16f1c84787c20",
"partyPlanToEventId": "59ef3b8136e16f1c84787c21",
"start": "2017-11-15T19:52:12",
"end": "2017-11-15T20:00:00",
"travelTimeString": "8 min.",
"travelTimeMinutes": 8,
"exceedsAvailableTime": false
},
{
"id": "59ef3b8036e16f1c84787c20-59ef3b8236e16f1c84787c22",
"partyPlanFromEventId": "59ef3b8036e16f1c84787c20",
"partyPlanToEventId": "59ef3b8236e16f1c84787c22",
"start": "2017-11-15T12:30:00",
"end": "2017-11-15T13:00:00",
"travelTimeString": "8 min.",
"travelTimeMinutes": 8,
"exceedsAvailableTime": true
},
{
"id": "59ef3b8036e16f1c84787c20-59ef3b8236e16f1c84787c23",
"partyPlanFromEventId": "59ef3b8036e16f1c84787c20",
"partyPlanToEventId": "59ef3b8236e16f1c84787c23",
"start": "2017-11-15T08:30:00",
"end": "2017-11-15T09:00:00",
"travelTimeString": "3 min.",
"travelTimeMinutes": 4,
"exceedsAvailableTime": true
}
],
"id": "59ef3b8236e16f1c84787c28",
"stringId": "59ef3b8236e16f1c84787c28"
}
}
// Transform data
const travelTimes = data.order.travelTimes.map(item => _.omit(item, ['id']) )
const orderLines = _.merge(data.order.orderLines, travelTimes)
const order = _.omit(data.order, ['orderLines', 'travelTimes'])
const orders = _.assign(order, { orderLines })
const addonGroups = _.groupBy(order.orderLines, 'connectedTo')
const addons = _.omit(addonGroups, 'undefined')
const products = _.pick(addonGroups, 'undefined')
const productGroups = _.groupBy(products.undefined, 'stringId')
console.log(productGroups) // All parent products
console.log(addons) // All addon products
const arr1 = _.values(_.flatMap(productGroups))
const arr2 = _.values(_.flatMap(addons))
Code on Codepen.io
Any help is greatly appreciated!
Let me know if I need to explain in further detail.
Not sure if I understood correctly what the expected result is, but I gave it a try anyway.
const orderLines = _(data.order.orderLines)
.map(item => {
if (!item.connectedTo) return _.assignIn(item, { addons: [] });
const match = _.find(data.order.orderLines, { id: item.connectedTo });
match.addons = match.addons || [];
match.addons.push(item);
return null;
})
.compact()
.value();
Check the output here: https://codepen.io/andreiho/pen/YEzQRd?editors=0012
I am having array in below format. i am having issue to append the value inside each chapter array. i need to add field like 'checked:true'. I need to get the data in same format. Expectation is, need same format with added one field inside chapter array.
{
"Books": [
{
"label":"Book1",
"data": [
{
"bookId": 3561,
"bookName": "AJ200",
"chapters": [
{
"id": 3926,
"name": "red"
},
{
"id": 3927,
"name": "yellow"
},
{
"id": 3928,
"name": "black"
}
]
}
]
},
{
"label":"Book2",
"data":[
{
"bookId": 3561,
"bookName": "AJ200",
"chapters": [
{
"id": 3564,
"name": "blue"
},
{
"id": 3565,
"name": "orange"
}
]
}
]
}
]
}
after adding field chapters array looks like as below,
"chapters": [
{
"id": 3564,
"name": "blue",
"checked":true
},
{
"id": 3565,
"name": "orange"
"checked":true
}
This is a little verbose but works all the same!
var myObject =
{
"Books": [
{
"label":"Book1",
"data": [
{
"bookId": 3561,
"bookName": "AJ200",
"chapters": [
{
"id": 3926,
"name": "red"
},
{
"id": 3927,
"name": "yellow"
},
{
"id": 3928,
"name": "black"
}
]
}
]
},
{
"label":"Book2",
"data":[
{
"bookId": 3561,
"bookName": "AJ200",
"chapters": [
{
"id": 3564,
"name": "blue"
},
{
"id": 3565,
"name": "orange"
}
]
}
]
}
]
}
var books = myObject.Books;
for(var i=0; i<books.length; i++) {
var bookData = books[i].data;
for(var j=0;j<bookData.length;j++) {
var chapters = bookData[j].chapters;
for(var k=0;k<chapters.length;k++) {
chapters[k].checked = true;
}
}
}
console.log(JSON.stringify(books));