I have the below output from Postman or hitting end point(we can say).
{
"SearchResult": {
"total": 11,
"resources": [
{
"id": "12345",
"name": "GuestType",
"description": "Identity group ",
},
{
"id": "56789",
"name": "Admin",
"description": "",
},
]
}
}
I want to extract "id" and "name" from these values. I see the values are inside sub-blocks.
How to extract these key-value using java-script that need to be put in "Tests" tab in postman?
var obj={
"SearchResult": {
"total": 11,
"resources": [
{
"id": "12345",
"name": "GuestType",
"description": "Identity group ",
},
{
"id": "56789",
"name": "Admin",
"description": "",
},
]
}
}
obj.SearchResult.resources.forEach((o)=>console.log(o.id,o.name));
Below code will return array of objects with id and name only.... Happy coding :)
let data = {
"SearchResult":
{
"total": 11,
"resources": [
{ "id": "12345", "name": "GuestType", "description": "Identity group ", },
{ "id": "56789", "name": "Admin", "description": "", }
]
}
}
let ids = data.SearchResult.resources.map(obj => {
id: obj.id,
name: obj.name
});
Try
let ids = data.SearchResult.resources.map(obj => obj.id);
let names = data.SearchResult.resources.map(obj => obj.name);
let data={ "SearchResult": { "total": 11, "resources": [ { "id": "12345", "name": "GuestType", "description": "Identity group ", }, { "id": "56789", "name": "Admin", "description": "", }, ] } }
let ids = data.SearchResult.resources.map(obj => obj.id);
let names = data.SearchResult.resources.map(obj => obj.name);
console.log(ids);
console.log(names);
Related
I have restaurant data array , I should make another array by grouping items by category that belongs to , I should convert this array :
[
{
"category": {
"title": "Appetizers",
},
"id": 1,
"price": "10",
"title": "Spinach Artichoke Dip",
},
{
"category": {
"title": "Appetizers",
},
"id": 2,
"price": "10",
"title": "Hummus",
},
{
"category": {
"title": "Salads",
},
"id": 3,
"price": "7",
"title": "Greek",
},
{
"category": {
"title": "Salads",
},
"id": 4,
"price": "9",
"title": "Beyn",
}
]
into a new array that should be as final result like this:
[{
"category": "Appetizers",
"items" : ["Spinach Artichoke Dip","Hummus"]
},
{
"category" : "Salads",
"items" :["Greek", "Beyn"]
}
]
I can't find how to do it could you please help
Lets say that your data is a constant called data
So you can do this:
const data = [
{
"category": {
"title": "Appetizers",
},
"id": 1,
"price": "10",
"title": "Spinach Artichoke Dip",
},
{
"category": {
"title": "Appetizers",
},
"id": 2,
"price": "10",
"title": "Hummus",
},
{
"category": {
"title": "Salads",
},
"id": 3,
"price": "7",
"title": "Greek",
},
{
"category": {
"title": "Salads",
},
"id": 4,
"price": "9",
"title": "Beyn",
}
];
const result = [];
data.forEach((item) => {
const category = item.category.title;
const title = item.title;
let foundCategory = result.find((c) => c.category === category);
if (foundCategory) {
foundCategory.items.push(title);
} else {
result.push({ category, items: [title] });
}
});
console.log(result);
Now your desired result will be stored in result
happy coding
const itemsToCategories = (itemsArr) => {
const store = {};
itemsArr.forEach(item => {
const categoryTitle = item.category.title;
if (!store[categoryTitle]) store[categoryTitle] = [];
store[categoryTitle].push(item.title);
});
return Object.entries(store).map(([category, items]) => ({ category, items}));
};
This solution should be a bit faster than the accepted answer for large data sets. The main difference is the use of an object (store) instead of an array, so lookups by the category title are more efficient. Then we build an array from that object at the end.
This does have more overhead than the accepted solution above, so for smaller data sets, this ends up being slower in comparison.
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)
I have the following data that is an array of nested objects:
"categories": [
{
"id": 1,
"name": "Category 1",
"years": [
{ "id": 1, "name": "1" },
{ "id": 2, "name": "2" }
]
},
{
"id": 2,
"name": "Category 2",
"years": [
{ "id": 2, "name": "2" },
{ "id": 3, "name": "3" }
]
}
]
I want to extract unique years in a separate array (desired output):
[
{ "id": 1, "name": "1" },
{ "id": 2, "name": "2" },
{ "id": 3, "name": "3" },
]
When I map out the years, I'm getting an array of arrays, how should I extract the unique objects for years?
let years = categories.map( (c) => { return c.years })
You can use a Map to filter duplicate years from the array of values using id as the key, and reduce() on both categories and years using the map as the accumulator:
const categories = [{
"id": 1,
"name": "Category 1",
"years": [
{ "id": 1, "name": "1" },
{ "id": 2, "name": "2" }
]
},
{
"id": 2,
"name": "Category 2",
"years": [
{ "id": 2, "name": "2" },
{ "id": 3, "name": "3" }
]
}
];
const years = categories.reduce(
(map, category) => category.years.reduce(
(map, year) => map.set(year.id, year),
map
),
new Map()
);
console.log([...years.values()]);
You can use reduce and Map
let data = [{"id": 1,"name": "Category 1","years": [{ "id": 1, "name": "1" },{ "id": 2, "name": "2" }]},{"id": 2,"name": "Category 2","years": [{ "id": 2, "name": "2" },{ "id": 3, "name": "3" }]}]
let final = data.reduce((op,{years}) => {
years.forEach(({id, name}) => {
let key = id + '-' + name
op.set(key, op.get(key) || {id, name})
})
return op
},new Map())
console.log([...final.values()])
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)
})
})
I want to build an new JSON from existing one. The source has sections and rubrics that I no longer need for a listing. The new object called 'items' should have an array of the items.
The final JSON should be sorted by attribute 'name' and look like
{
"items": [
{
"id": 10000006,
"name": "Boah"
},
{
"id": 10000013,
"name": "Gut"
},
{
"id": 10000003,
"name": "Ipsum"
},
{
"id": 10000001,
"name": "Lorem"
},
{
"id": 10000005,
"name": "Lorum"
},
{
"id": 10000004,
"name": "Name"
},
{
"id": 10000002,
"name": "Stet"
}
]
}
For building the new JSON I get this source:
{
"sections": [
{
"name": "FooBar",
"rubrics": [
{
"name": "Foo",
"items": [
{
"id": 10000001,
"name": "Lorem"
},
{
"id": 10000002,
"name": "Stet"
},
{
"id": 10000003,
"name": "Ipsum"
}
]
},
{
"name": "Bar",
"items": [
{
"id": 10000004,
"name": "Name"
},
{
"id": 10000005,
"name": "Lorum"
},
{
"id": 10000006,
"name": "Boah"
}
]
}
]
},
{
"name": "BlahBloob",
"rubrics": [
{
"name": "Bla",
"items": [
{
"id": 10000013,
"name": "Gut"
}
]
},
{
"name": "Bloob",
"items": [
{
"id": 10000014,
"name": "Name"
},
{
"id": 10000015,
"name": "Lorem"
}
]
}
]
}
]
}
What do you think? How can I do this with plain JavaScript or maybe TypeScript?
Thanks for reading and have time for my question. And thanks for reply in advance.
Here you go. You just need to iterate over each rubric of each section of your source to get the items. At the end, sort your list of items by items, and you're done.
This example uses ES6 syntax, but it's easy to convert it to ES5 if needed.
function extractItems(source) {
const items = [];
for (const section of source.sections) {
for (const rubric of section.rubrics) {
items.push(...rubric.items);
}
}
items.sort((a, b) => a.name.localeCompare(b.name));
return { items };
}
A more functional approach use map and reduce to pick the rubrics and merge them.
data.sections
.map(section => section.rubrics) // get rubrics
.reduce((a, b) => a.concat(b)) // merge rubrics
.map(rubric => rubric.items) // get items from each rubric
.reduce((a, b) => a.concat(b)) // merge items
.sort((a, b) => a.name.localeCompare(b.name)); // sort
function(oldObj) {
var newObj = {
"items": []
};
oldObj.sections.forEach(function(section) {
section.rubrics.forEach(function(rubric) {
rubric.items.forEach(function(item) {
newObj.items.push(item);
});
});
});
newObj.items = newObj.items.sort(function(a, b) {
if (a.name < b.name) { return -1; }
if (a.name > b.name) { return 1; }
return 0;
});
return newObj;
}
And simply use JSON.parse() and JSON.stringify() to convert JSON to and from objects.
It might help you
var data ={
"sections": [
{
"name": "FooBar",
"rubrics": [{"name": "Foo", "items": [{"id": 10000001,"name": "Lorem"}, {"id": 10000002,"name": "Stet"}, {"id": 10000003,"name": "Ipsum"}]
}, {
"name": "Bar",
"items": [{
"id": 10000004,
"name": "Name"
}, {
"id": 10000005,
"name": "Lorum"
}, {
"id": 10000006,
"name": "Boah"
}]
}]
}, {
"name": "BlahBloob",
"rubrics": [{
"name": "Bla",
"items": [{
"id": 10000013,
"name": "Gut"
}]
}, {
"name": "Bloob",
"items": [{
"id": 10000014,
"name": "Name"
}, {
"id": 10000015,
"name": "Lorem"
}]
}]
}]
};
var itemObj = {};
var itemArr = [];
var sections = data.sections;
for(var i=0;i<sections.length;i++)
{
for(var j=0;j<sections[i].rubrics.length;j++){
for(var k=0;k<sections[i].rubrics[j].items.length;k++){
var itemObj;
itemObj['id'] = sections[i].rubrics[j].items[k].id;
itemObj['name'] = sections[i].rubrics[j].items[k].name;
itemArr.push(itemObj);
}
}
}
var finalObj = {"items":itemArr};
console.log(finalObj);
JSFiddle