I have the following JSON object:
{
"name": "Womens",
"position": 1,
"url": "/collections/womens-all",
"submenus": [
{
"name": "Apparel",
"position": 1,
"url": "/collections/womens-apparel-all",
"submenus": [
{
"name": "Tees & Tanks",
"position": 1,
"url": "/collections/womens-tees",
"submenus": []
},
{
"name": "Silk & Tops",
"position": 2,
"url": "/collections/womens-tops",
"submenus": []
},
{
"name": "Sweaters & Sweatshirts",
"position": 3,
"url": "/collections/womens-sweaters",
"submenus": []
}
]
},
{
"name": "Accessories",
"position": 2,
"url": "/collections/womens-all-accessories",
"submenus": [
{
"name": "Petra",
"position": 1,
"url": "/collections/petra",
"submenus": []
},
{
"name": "Weekenders",
"position": 2,
"url": "/collections/womens-bags",
"submenus": []
},
{
"name": "Backpacks & Totes",
"position": 3,
"url": "/collections/womens-backpacks",
"submenus": []
},
{
"name": "Accessories & Shoes",
"position": 4,
"url": "/collections/womens-accessories",
"submenus": []
}
]
}
]
}
I want to flatten this object's submenus into a single array containing every menu in the tree. The result would look like:
[
{
"name": "Apparel",
"position": 1,
"url": "/collections/womens-apparel-all",
"submenus": []
},
{
"name": "Accessories",
"position": 2,
"url": "/collections/womens-all-accessories",
"submenus": []
},
{
"name": "Petra",
"position": 1,
"url": "/collections/petra",
"submenus": []
},
{
"name": "Weekenders",
"position": 2,
"url": "/collections/womens-bags",
"submenus": []
},
{
"name": "Backpacks & Totes",
"position": 3,
"url": "/collections/womens-backpacks",
"submenus": []
},
{
"name": "Accessories & Shoes",
"position": 4,
"url": "/collections/womens-accessories",
"submenus": []
},
{
"name": "Tees & Tanks",
"position": 1,
"url": "/collections/womens-tees",
"submenus": []
},
{
"name": "Silk & Tops",
"position": 2,
"url": "/collections/womens-tops",
"submenus": []
},
{
"name": "Sweaters & Sweatshirts",
"position": 3,
"url": "/collections/womens-sweaters",
"submenus": []
}
]
I feel like a recursive solution would be best, but I can't get it right. What would be the best approach for this problem?
This should do, assuming you forgot "Womens" in the resulting array in your example:
def flatten(dct, res=None):
if res is None:
res = []
subdct = {}
for k in dct:
v = dct[k]
if k == "submenus":
for e in v:
flatten(e, res)
v = []
subdct[k] = v
res.append(subdct)
return res
to be called like
result = flatten(json_object)
Related
I'm working with vue-draggable for creating a navigation menu. The result array could have N deep levels.
I want to remove an object by it's id.
The array looks like:
[
{
"id": 1,
"name": "Viedma",
"slug": "viedma",
"children": []
},
{
"id": 6,
"name": "Cultura",
"slug": "Cultura",
"children": [
{
"id": 2,
"name": "Rio Negro",
"slug": "rio-negro",
"children": [
{
"id": 4,
"name": "Edictos",
"slug": "edictos",
"children": []
},
{
"id": 5,
"name": "Deportes",
"slug": "deportes",
"children": []
}
]
}
]
},
{
"id": 3,
"name": "Policiales",
"slug": "policiales",
"children": []
}
]
I've tried the solution from remove object from nested array but since I have an array instead of a main object it doesn't work.
Please note that I'm using vue 3 with composition API.
This is what I have so far. The remove() method is called from UI
setup(props, context) {
const resources = ref(props.data)
const removeFromTree = (parent, childNameToRemove) => {
parent.children = parent.children
.filter(function(child){ return child.name !== childNameToRemove})
.map(function(child){ return removeFromTree(child, childNameToRemove)})
return parent
}
const remove = (element) => {
var tree = [...resources.value]
resources.value = removeFromTree(tree, element.name)
}
return {
resources,
remove
}
}
BTW, If parent is removed, all it's children should be removed too.
Your function takes parent as an object but you passing tree as an array. You can do like this
function removeItemByName(items, itemName) {
return items.filter(item => item.name !== itemName)
.map(item => {
item.children = removeItemByName(item.children, itemName)
return item
})
}
const input = [
{
"id": 1,
"name": "Viedma",
"slug": "viedma",
"children": []
},
{
"id": 6,
"name": "Cultura",
"slug": "Cultura",
"children": [
{
"id": 2,
"name": "Rio Negro",
"slug": "rio-negro",
"children": [
{
"id": 4,
"name": "Edictos",
"slug": "edictos",
"children": []
},
{
"id": 5,
"name": "Deportes",
"slug": "deportes",
"children": []
}
]
}
]
},
{
"id": 3,
"name": "Policiales",
"slug": "policiales",
"children": []
}
]
console.log(removeItemByName(input, 'Policiales'))
console.log(removeItemByName(input, 'Deportes'))
I have an array :
{
"count": 8,
"id": "accountId",
"name": " Account Id",
"values": [
{
"count": 2,
"id": "1234456789000",
"name": "1234456789000"
},
{
"count": 1,
"id": "135792468045",
"name": "135792468045"
},
{
"count": 1,
"id": "309983110022",
"name": "309983110022"
},
{
"count": 2,
"id": "432112426686",
"name": "432112426686"
},
{
"count": 1,
"id": "6ee26149-a156-4665-bd26-a6e46b49a70f",
"name": "6ee26149-a156-4665-bd26-a6e46b49a70f"
},
{
"count": 1,
"id": "927b48ce-efe4-4c20-98f0-ec6c54f59b45",
"name": "927b48ce-efe4-4c20-98f0-ec6c54f59b45"
}
]
}
And I have a 2nd array :
[
{
"count": 2,
"id": "432112426686",
"name": "432112426686"
},
{
"count": 2,
"id": "1234456789000",
"name": "1234456789000"
}
]
The second array, I have filtered based on some requirement.
I want to replace the values from 1st array with second array.
Using typescript code.
Please help here.
If I understand question, you just need iterate by values array and find same id from second array.
function findAndSwitch(object1, array1): void {
object1.values = object1.values.map(el => {
const objToSwitch = array1.find(eleArr => eleArr.id === el.id);
if (objToSwitch) {
return el = objToSwitch;
} else {
return el;
}
});
}
https://stackblitz.com/edit/typescript-dvty4p
Let's say your variable names are obj1 and arr2, respectively. First transform arr2 into an object obj2:
let obj2 = arr2.reduce((acc,cur) => ({...acc,[cur.id]:cur}),{});
Which now looks like this:
{
'432112426686': {
count: 20,
id: '432112426686',
name: '432112426686'
},
'1234456789000': {
count: 20,
id: '1234456789000',
name: '1234456789000'
}
}
Then transform obj1 based on obj2 as follows:
obj1.values = obj1.values.map(value => obj2[value.id] || value);
Please note that since the data in arr2 is identical to the corresponding data in obj1, I have altered the values of count property in arr2 in order to demonstrate that obj1 will be updated accordingly.
DEMO ONE
let obj1 = {
"count": 8,
"id": "accountId",
"name": " Account Id",
"values": [
{
"count": 2,
"id": "1234456789000",
"name": "1234456789000"
},
{
"count": 1,
"id": "135792468045",
"name": "135792468045"
},
{
"count": 1,
"id": "309983110022",
"name": "309983110022"
},
{
"count": 2,
"id": "432112426686",
"name": "432112426686"
},
{
"count": 1,
"id": "6ee26149-a156-4665-bd26-a6e46b49a70f",
"name": "6ee26149-a156-4665-bd26-a6e46b49a70f"
},
{
"count": 1,
"id": "927b48ce-efe4-4c20-98f0-ec6c54f59b45",
"name": "927b48ce-efe4-4c20-98f0-ec6c54f59b45"
}
]
};
let arr2 = [
{
"count": 20,
"id": "432112426686",
"name": "432112426686"
},
{
"count": 20,
"id": "1234456789000",
"name": "1234456789000"
}
];
let obj2 = arr2.reduce((acc,cur) => ({...acc,[cur.id]:cur}),{});
obj1.values = obj1.values.map(value => obj2[value.id] || value);
console.log( obj1 );
--
However, if all you want is to replace all the obj1.values with arr2, all you need is:
obj1.values = [...arr2];
And this will give rise to:
{
count: 8,
id: 'accountId',
name: ' Account Id',
values: [{
count: 20,
id: '432112426686',
name: '432112426686'
},
{
count: 20,
id: '1234456789000',
name: '1234456789000'
}
]
}
DEMO TWO
let obj1 = {
"count": 8,
"id": "accountId",
"name": " Account Id",
"values": [
{
"count": 2,
"id": "1234456789000",
"name": "1234456789000"
},
{
"count": 1,
"id": "135792468045",
"name": "135792468045"
},
{
"count": 1,
"id": "309983110022",
"name": "309983110022"
},
{
"count": 2,
"id": "432112426686",
"name": "432112426686"
},
{
"count": 1,
"id": "6ee26149-a156-4665-bd26-a6e46b49a70f",
"name": "6ee26149-a156-4665-bd26-a6e46b49a70f"
},
{
"count": 1,
"id": "927b48ce-efe4-4c20-98f0-ec6c54f59b45",
"name": "927b48ce-efe4-4c20-98f0-ec6c54f59b45"
}
]
};
let arr2 = [
{
"count": 20,
"id": "432112426686",
"name": "432112426686"
},
{
"count": 20,
"id": "1234456789000",
"name": "1234456789000"
}
];
obj1.values = arr2;
console.log( obj1 );
I have an array of object like this :
[
{
"url": "https://recipes-gatsby-react.netlify.app/",
"stack": [
{
"id": 1,
"title": "GatsbyJs"
},
{
"id": 2,
"title": "React"
},
{
"id": 3,
"title": "GraphQl"
}
],
"id": "Project_1",
"featured": false,
"title": "Gatsby recipes app"
},
{
"url": "https://resort-react-mr.netlify.app",
"stack": [
{
"id": 4,
"title": "React"
},
{
"id": 5,
"title": "Contentful"
}
],
"id": "Project_2",
"featured": false,
"title": "react resort"
},
{
"url": "https://color-generator-react-mr.netlify.app/",
"stack": [
{
"id": 6,
"title": "React"
}
],
"id": "Project_3",
"featured": false,
"title": "color generator"
},
{
"url": "",
"stack": [
{
"id": 7,
"title": "React Native"
},
{
"id": 8,
"title": "Firebase"
}
],
"id": "Project_4",
"featured": false,
"title": "Book-Worm"
},
{
"url": "",
"stack": [
{
"id": 9,
"title": "React Native"
},
{
"id": 10,
"title": "Firebase"
},
{
"id": 11,
"title": "Stripe"
},
{
"id": 12,
"title": "Google Api"
}
],
"id": "Project_5",
"featured": false,
"title": "Delivery App"
},
{
"url": "https://cocktails-react-app-mr.netlify.app/",
"stack": [
{
"id": 13,
"title": "React"
}
],
"id": "Project_6",
"featured": false,
"title": "Cocktails App"
},
{
"url": "https://www.ideacasaitalia.it/index.php",
"stack": [
{
"id": 14,
"title": "Prestashop"
}
],
"id": "Project_7",
"featured": false,
"title": "Idea Casa Italia"
}
]
and I have another (simple) array like this one for example
["react","prestashop"]
I would like to filter the first array based on STACK key on the value of the second array, i.e. I would like to be returned all elements that have at least one element of the array (variable).
I have come to this
const filter = value => {
const newProj = relProjects.filter(obj =>
obj.stack.some(st => st.title.toLowerCase().includes(value))
)
setProjRel(newProj)
}
console.log(filter(["react","prestashop"])
however in this way I can only get the elements that contain all the elements of the array. Instead I would like to have returned all the elements that have AT LEAST 1 stack of the ones I passedThanks to who will answer me
Using Array#filter and Array#includes
Filter through the data array. With the predicate being that the stack array has at least one item that is included in the matches array
const data = [{"url":"https://recipes-gatsby-react.netlify.app/","stack":[{"id":1,"title":"GatsbyJs"},{"id":2,"title":"React"},{"id":3,"title":"GraphQl"}],"id":"Project_1","featured":false,"title":"Gatsby recipes app"},{"url":"https://resort-react-mr.netlify.app","stack":[{"id":4,"title":"React"},{"id":5,"title":"Contentful"}],"id":"Project_2","featured":false,"title":"react resort"},{"url":"https://color-generator-react-mr.netlify.app/","stack":[{"id":6,"title":"React"}],"id":"Project_3","featured":false,"title":"color generator"},{"url":"","stack":[{"id":7,"title":"React Native"},{"id":8,"title":"Firebase"}],"id":"Project_4","featured":false,"title":"Book-Worm"},{"url":"","stack":[{"id":9,"title":"React Native"},{"id":10,"title":"Firebase"},{"id":11,"title":"Stripe"},{"id":12,"title":"Google Api"}],"id":"Project_5","featured":false,"title":"Delivery App"},{"url":"https://cocktails-react-app-mr.netlify.app/","stack":[{"id":13,"title":"React"}],"id":"Project_6","featured":false,"title":"Cocktails App"},{"url":"https://www.ideacasaitalia.it/index.php","stack":[{"id":14,"title":"Prestashop"}],"id":"Project_7","featured":false,"title":"Idea Casa Italia"}];
const matches = ["react", "prestashop"];
const filtered = data.filter(({ stack }) => stack.filter(({ title }) => matches.includes(title.toLowerCase())).length > 0);
console.log(filtered);
Good morning, can anyone advise me? I'm pretty clueless. I've already spent a few hours on it and I don't know how to solve this.
The data is fictitious and the original JSON is far more complex.
JSON
{
"main": [
[
{
"type": "dasdasdasd",
"id": 5,
"content": {
"title": "adadadsad",
"items": [
{
"date": "2012-02-02T11:23:00Z",
"id": 12,
"name": "test",
"isEnabled": false,
"isHighlited": false,
"images": {
"lists": {
"small": [
{
"id": 18,
"position": 0,
"titleImage": true,
"url": "",
"thumbnailReady": true
}
],
"original": [
{
"id": 19,
"position": 0,
"titleImage": true,
"url": "",
"thumbnailReady": true
}
],
"large": [
{
"id": 22,
"position": 0,
"titleImage": true,
"url": "",
"thumbnailReady": true
}
],
"medium": [
{
"id": 23,
"position": 0,
"titleImage": true,
"url": "",
"thumbnailReady": true
}
]
}
},
"enum": "LINIE",
"url": "https://test.com"
}
]
}
}
]
],
"second": [
]
}
How can I get from main -> content -> items -> images -> url?
More precisely each images and from that url.
Thank you very much in advance for your help.
It looks like your main array has an array as 1st element. If that is correct, you take the first element of main, and then loop over that.
let jsonObj = {
"main": [
[
{
"type": "dasdasdasd",
"id": 5,
"content": {
"title": "adadadsad",
"items": [
{
"date": "2012-02-02T11:23:00Z",
"id": 12,
"name": "test",
"isEnabled": false,
"isHighlited": false,
"images": {
"lists": {
"small": [
{
"id": 18,
"position": 0,
"titleImage": true,
"url": "",
"thumbnailReady": true
}
],
"original": [
{
"id": 19,
"position": 0,
"titleImage": true,
"url": "",
"thumbnailReady": true
}
],
"large": [
{
"id": 22,
"position": 0,
"titleImage": true,
"url": "",
"thumbnailReady": true
}
],
"medium": [
{
"id": 23,
"position": 0,
"titleImage": true,
"url": "",
"thumbnailReady": true
}
]
}
},
"enum": "LINIE",
"url": "https://test.com"
}
]
}
}
]
],
"second": [
]
}
let smallImg = "", originalImg = "", largeImg = "", mediumImg = "";
jsonObj.main[0].forEach(mainItem => {
mainItem.content.items.forEach(item => {
smallImg = item.images.lists.small[0].url;
originalImg = item.images.lists.original[0].url;
largeImg = item.images.lists.large[0].url;
mediumImg = item.images.lists.medium[0].url;
});
});
console.log(smallImg);
console.log(originalImg);
console.log(largeImg);
console.log(mediumImg);
I am trying to make a shopping cart API route and I am stuck with this problem because when I am using this statement $carts = \Cart::session($session)->getContent();
I get an object like this:
"cart": {
"1": {
"id": 1,
"name": "Tort cu biscuiți",
"price": 20,
"quantity": "1",
"attributes": {
"image_path": "http://127.0.0.1:8000/storage/images/AkiGKJdxjKNtyoVI034RPL1drLsMntUxLfzqZplV.jpeg"
},
"conditions": []
},
"2": {
"id": 2,
"name": "Tort cu biscuiți",
"price": 20,
"quantity": 2,
"attributes": {
"image_path": "http://127.0.0.1:8000/storage/images/IkAhenLttHWaRD58hNZ460ykWCq7q1sih3vI9H5V.jpeg"
},
"conditions": []
}
}
and I want to convet this to be array of objects. I tryied $cart->toArray(); and didn't work, also I tiyed (array) $cart and I get this:
"cart": {
"\u0000*\u0000items": {
"1": {
"id": 1,
"name": "Tort cu biscuiți",
"price": 20,
"quantity": "1",
"attributes": {
"image_path": "http://127.0.0.1:8000/storage/images/AkiGKJdxjKNtyoVI034RPL1drLsMntUxLfzqZplV.jpeg"
},
"conditions": []
},
"2": {
"id": 2,
"name": "Tort cu biscuiți",
"price": 20,
"quantity": 2,
"attributes": {
"image_path": "http://127.0.0.1:8000/storage/images/IkAhenLttHWaRD58hNZ460ykWCq7q1sih3vI9H5V.jpeg"
},
"conditions": []
}
}
}
may I know what is the problem?
You can do it manuel like this:
$carts = \Cart::session($session)->getContent();
if ($carts) {
$cartsArray = json_decode($carts);
foreach($cartsArray->cart as &$cart){
$cart = (array) $cart;
}
}
dd($cartsArray);