How to get the respective JSON object based on id - javascript

how to get the respective nested JSON object based on Id. For example below is my complete JSON.
[
{
"id": 1,
"title": "ASD Headquarters",
"items": [
{
"id": 11,
"title": "San Jose",
"items": [
{
"id": 13,
"title": "Jensen Chapman's Team",
"items": [
{
"id": 14,
"title": "Jimmy John"
},
{
"id": 15,
"title": "Daniel Mills"
},
{
"id": 16,
"title": "Chris Boden"
}
]
}
]
},
{
"id": 12,
"title": "Irvine",
"items": [
{
"id": 23,
"title": "Tracey Chapman's Team",
"items": [
{
"id": 24,
"title": "San Jesus"
},
{
"id": 25,
"title": "Fat Albert"
},
{
"id": 26,
"title": "Connor McDavid"
}
]
}
]
},
{
"id": 30,
"title": "San Diego",
"items": [
{
"id": 31,
"title": "Duran Duran's Team",
"items": [
{
"id": 32,
"title": "Amberlynn Pinkerton"
},
{
"id": 33,
"title": "Tony Mejia"
},
{
"id": 34,
"title": "Richard Partridge"
},
{
"id": 35,
"title": "Elliot Stabler"
}
]
},
{
"id": 40,
"title": "Steely Dan's Team",
"items": [
{
"id": 36,
"title": "Tony Stark"
},
{
"id": 37,
"title": "Totally Rad"
},
{
"id": 38,
"title": "Matt Murdock"
},
{
"id": 39,
"title": "Stan Lee"
}
]
}
]
}
]
}
]
From the above json how do i filter only particular nested object which have id as 11 => {"id": 11} using underscore.js
Output which i required is : {
"id":11,
"title":"San Jose",
"items":[
{
"id":13,
"title":"Jensen Chapman's Team",
"items":[
{
"id":14,
"title":"Jimmy John"
},
{
"id":15,
"title":"Daniel Mills"
},
{
"id":16,
"title":"Chris Boden"
}
]
}
]
}

You can use a recursive algorithm to look for an object in the current array as well as the nested ones.
var data = [{"id":1,"title":"ASD Headquarters","items":[{"id":11,"title":"San Jose","items":[{"id":13,"title":"Jensen Chapman's Team","items":[{"id":14,"title":"Jimmy John"},{"id":15,"title":"Daniel Mills"},{"id":16,"title":"Chris Boden"}]}]},{"id":12,"title":"Irvine","items":[{"id":23,"title":"Tracey Chapman's Team","items":[{"id":24,"title":"San Jesus"},{"id":25,"title":"Fat Albert"},{"id":26,"title":"Connor McDavid"}]}]},{"id":30,"title":"San Diego","items":[{"id":31,"title":"Duran Duran's Team","items":[{"id":32,"title":"Amberlynn Pinkerton"},{"id":33,"title":"Tony Mejia"},{"id":34,"title":"Richard Partridge"},{"id":35,"title":"Elliot Stabler"}]},{"id":40,"title":"Steely Dan's Team","items":[{"id":36,"title":"Tony Stark"},{"id":37,"title":"Totally Rad"},{"id":38,"title":"Matt Murdock"},{"id":39,"title":"Stan Lee"}]}]}]}];
console.log(find(12, data));
function find(id, [head, ...tail]) {
if (!head)
return null;
return checkObj(id, head) || find(id, tail);
}
function checkObj(id, obj) {
return obj.id === id ? obj : find(id, obj.items || [])
}
This also uses parameter destructuring in order to conveniently separate the "head" of the array from its "tail".
It could also be done within a single function.
var data = [{"id":1,"title":"ASD Headquarters","items":[{"id":11,"title":"San Jose","items":[{"id":13,"title":"Jensen Chapman's Team","items":[{"id":14,"title":"Jimmy John"},{"id":15,"title":"Daniel Mills"},{"id":16,"title":"Chris Boden"}]}]},{"id":12,"title":"Irvine","items":[{"id":23,"title":"Tracey Chapman's Team","items":[{"id":24,"title":"San Jesus"},{"id":25,"title":"Fat Albert"},{"id":26,"title":"Connor McDavid"}]}]},{"id":30,"title":"San Diego","items":[{"id":31,"title":"Duran Duran's Team","items":[{"id":32,"title":"Amberlynn Pinkerton"},{"id":33,"title":"Tony Mejia"},{"id":34,"title":"Richard Partridge"},{"id":35,"title":"Elliot Stabler"}]},{"id":40,"title":"Steely Dan's Team","items":[{"id":36,"title":"Tony Stark"},{"id":37,"title":"Totally Rad"},{"id":38,"title":"Matt Murdock"},{"id":39,"title":"Stan Lee"}]}]}]}];
console.log(find(12, data));
function find(id, [head, ...tail]) {
if (!head)
return null;
if (head.id === id)
return head;
return find(id, head.items || []) || find(id, tail);
}

Related

React - Filter Multidimensional array with another array

I want to return only matches results.
My array:
products: [
{
"id": 1,
"name": "Product 1",
"concepts": [
{
"id": 10,
"name": "Blabla"
},
{
"id": 15,
"name": "Zlazla"
}
]
},
{
"id": 2,
"name": "Product 2",
"concepts": [
{
"id": 14,
"name": "Gulagula"
},
{
"id": 15,
"name": "Zlazla"
}
]
}
]
I want to filter products which only have one of the concepts below.
concepts array:
['14', '15']
Couldn't solve this in an easy way.
You can try this way:
var products= [
{
"id": 1,
"name": "Product 1",
"concepts": [
{
"id": 10,
"name": "Blabla"
},
{
"id": 15,
"name": "Zlazla"
}
]
},
{
"id": 2,
"name": "Product 2",
"concepts": [
{
"id": 14,
"name": "Gulagula"
},
{
"id": 15,
"name": "Zlazla"
}
]
}
]
var products = products.filter((product) => product.concepts = product.concepts.filter( (x) => x.id == 14 || x.id == 15));
console.log(products);

How to replace an array of objects with an array including newer objects in TypeScript?

For example: I have an array of objects like this:
let arrayOfObjects: [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
Now I want to replace or overwrite the array above with the same array, but including different values (same keys, different values):
let arrayOfObjects: [
{ "id": 0, "name": "Not Available" },
{ "id": 1, "name": "Not Ready" },
{ "id": 2, "name": "Not Started" }
];
How can this be done in TypeScript?
Try this JS
let oneArray = [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
let twoArray = [
{ "id": 0, "name": "Not Available" },
{ "id": 1, "name": "Not Ready" },
{ "id": 2, "name": "Not Started" }
];
let newArray = Object.assign([], oneArray, twoArray);
console.log(newArray);
In TS
interface Data {
oneArray: array;
twoArray: array;
}
function merge(data: Data) {
return Object.assign([], data.oneArray, data.twoArray);
}
let user = {
oneArray: [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
],
twoArray: [
{ "id": 0, "name": "Not Available" },
{ "id": 1, "name": "Not Ready" },
{ "id": 2, "name": "Not Started" }
]
};
console.log(merge(user));
Sure :)
let arrayOfObjects = [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
const newValues = ['Not Available', 'Not Ready', 'Not Started'];
newValues.forEach((value, i) => {
arrayOfObjects.find(o => o.id === i).name = value;
});
console.log(arrayOfObjects);
I wouldn't recommend this though: functional programming is awesome.
let arrayOfObjects = [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
let names = ['Not Available', 'Not Ready', 'Not Started']
let result = arrayOfObjects.map((user, index) => ({ ...user, name: names[index] }))
console.log(result)

Grouping a multilevel array of objects

I am trying to learn javascript reduce and map an I came across some difficulties.
I have an array with the following format. The id of the parent is same as the location_id of the child. I need to group the array into a nested format.
arr = [
{
"id": 4583211,
"name": "Location 1",
"location_id": null,
},
{
"id": 7458894,
"name": "Location 12",
"location_id": 4583211
},
{
"id": 7463953,
"name": "Location 13",
"location_id": 4583211
},
{
"id": 80302210,
"name": "Location 121",
"location_id": 7458894
},
{
"id": 80302219,
"name": "Location 122",
"location_id": 7458894
},
{
"id": 7464314,
"name": "Location 131",
"location_id": 7463953
},
{
"id": 4583216,
"name": "Location 2",
"location_id": null,
},
{
"id": 3566353,
"name": "Location 21",
"location_id": 4583216
},
]
This array should be grouped as:
result = [
{
"id": 4583211,
"name": "Location 1",
"locations": [
{
"id": 7458894,
"name": "Location 12",
"locations": [
{
"id": 80302210,
"name": "Location 121"
},
{
"id": 80302219,
"name": "Location 122"
}
]
},
{
"id": 7463953,
"name": "Location 13",
"locations": [
{
"id": 7464314,
"name": "Location 131"
}
]
}
]
},
{
"id": 4583216,
"name": "Location 2",
"locations": [
{
"id": 3566353,
"name": "Location 21"
}
]
}
]
I tried to group it using the following method found on SO but it gives different result.
result = arr.reduce(function (r, a) {
r[a.location_id] = r[a.location_id] || [];
r[a.location_id].push(a);
return r;
}, Object.create(null));
You could do this using reduce and recursion you just need to check if parent is equal to current elements location_id.
const data = [{"id":4583211,"name":"Location 1","location_id":null},{"id":7458894,"name":"Location 12","location_id":4583211},{"id":7463953,"name":"Location 13","location_id":4583211},{"id":80302210,"name":"Location 121","location_id":7458894},{"id":80302219,"name":"Location 122","location_id":7458894},{"id":7464314,"name":"Location 131","location_id":7463953},{"id":4583216,"name":"Location 2","location_id":null},{"id":3566353,"name":"Location 21","location_id":4583216}]
function create(data, parent = null) {
return data.reduce((r, e) => {
if(parent == e.location_id) {
const o = { id: e.id, name: e.name }
const children = create(data, e.id);
if(children.length) o.locations = children;
r.push(o)
}
return r
}, [])
}
console.log(create(data))

Return filtered array js

I have an Array of Objects, each containing Array and Objects, like so:
data = [{
"id": 10022,
"date": "2017-12-31T03:44:19.963808Z",
"bought_beats": [{
"id": 10034,
"beat": {
"id": 6334,
"name": "Glass",
"producer": {
"id": 23,
"display_name": "MadReal",
}
},
"license": {
"id": 10034,
"name": "Premium",
},
}, {
"id": 894,
"beat": {
"id": 6334,
"name": "Other Name",
"producer": {
"id": 25,
"display_name": "Other Name",
}
},
"license": {
"id": 10034,
"name": "Premium",
},
}]
}, {
"moredata": "stuff"
}]
And I need to filter the bought_beats property, and only return beat, if beat.producer.id === 23
This is what I have but it's clearly not working
data.forEach(order => {
return order.bought_beats.filter(item => item.beat.id === producerId)
})
===========
Edit1:
Trying this. It "works", but it also removed some properties (id & date) from each order object (which is each index of data), so I have objects that only contain the array of "bought_beats"
var res = data.map(item => item.bought_beats.filter(item => item.beat.producer.id === 23))
========
Edit2
This seems to be 1 solution, it maintains the array and object structure the same, while it removes those unwanted elements from the bought_beats array.
data.forEach(order => {
let elementToRemoveIndex = order.bought_beats.findIndex(item => item.beat.producer.id !== 23)
order.bought_beats.splice(elementToRemoveIndex, 1)
})
Thanks #Pac0 for the continuous help
use .find over data.bought_beats since its an array,
DEMO
var data = [{
"id": 10022,
"date": "2017-12-31T03:44:19.963808Z",
"bought_beats": [{
"id": 10034,
"beat": {
"id": 6334,
"name": "Glass",
"producer": {
"id": 23,
"display_name": "MadReal",
}
},
"license": {
"id": 10034,
"name": "Premium",
},
}, {
"id": 894,
"beat": {
"id": 6334,
"name": "Other Name",
"producer": {
"id": 25,
"display_name": "Other Name",
}
},
"license": {
"id": 10034,
"name": "Premium",
},
}]
}, {
"moredata": "stuff"
}];
var result = data.find(dat => dat.bought_beats.some(item => item.beat.producer.id === 23));
console.log(result);
If I understood correctly, this should be what you want :
// project each object to its bought_beats / beats part
var beatsArrays = data.filter(x => x.bought_beats).map(x => x.bought_beats);
// flatten the array of arrays of beats into a simple array of beats
var beats = [].concat.apply([],beatsArrays).map(x => x.beat);
// filter
var relevantBeats = beats.filter(item => item.producer.id === 23);
// serve with a cherry in a sugar-frost cocktail glass (happy new year ! )
console.log(relevantBeats);
Snippet :
data = [{
"id": 10022,
"date": "2017-12-31T03:44:19.963808Z",
"bought_beats": [{
"id": 10034,
"beat": {
"id": 6334,
"name": "Glass",
"producer": {
"id": 23,
"display_name": "MadReal",
}
},
"license": {
"id": 10034,
"name": "Premium",
},
}, {
"id": 894,
"beat": {
"id": 6334,
"name": "Other Name",
"producer": {
"id": 25,
"display_name": "Other Name",
}
},
"license": {
"id": 10034,
"name": "Premium",
},
}]
}, {
"moredata": "stuff"
}];
// project each object to its bought_beats / beats part
var beatsArrays = data.filter(x => x.bought_beats).map(x => x.bought_beats);
// flatten the array of arrays of beats into a simple array of beats
var beats = [].concat.apply([],beatsArrays).map(x => x.beat);
// filter
var relevantBeats = beats.filter(item => item.producer.id === 23);
// serve with a cherry in a sugar-frost cocktail glass (happy new year ! )
console.log(relevantBeats);
// for each order
data.forEach(order => {
// we loop thorugh the bought beats array
order.bought_beats.forEach((item, index) => {
// and if there's a beat from another producer, we remove it
if (item.beat.producer.id !== producerId) order.bought_beats.splice(index, 1)
})
})

Lodash filter nested object

I have the following object containing an array posts:
var posts = {
"posts": [{
"id": 83,
"title": "Onfido helps iCracked win customers’ confidence",
"slug": "onfido-helps-icracked-win-customers-confidence",
"tags": [{
"id": 25,
"slug": "case-studies"
}, {
"id": 10,
"slug": "industry-news"
}]
}, {
"id": 82,
"title": "Machine learning makes banking more personal",
"slug": "machine-learning-makes-banking-more-personal",
"tags": [{
"id": 10,
"slug": "industry-news"
}]
}, {
"id": 81,
"title": "11 reasons to join Onfido",
"slug": "ten-reasons-to-join-onfido",
"tags": [{
"id": 100,
"slug": "our-expertise"
}]
}]
}
Using Lodash, I’d like to extract all posts with tags.slug of value "case-studies". Currently I’ve been trying the following with no luck:
_.filter(posts, function(post) {
_.filter(post.tags, function(tag) {
return _.where(tag, {'slug': 'case-studies'})
})
})
How would I do this?
Lodash
var out = _.filter(posts.posts, function (post) {
return _.some(post.tags, { 'slug': 'case-studies' });
});
Vanilla JS
var out = posts.posts.filter(function (el) {
return el.tags.some(function (tag) {
return tag.slug === 'case-studies';
});
});

Categories

Resources