Iteration Javascript objects [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Write a function that can take any number of episode ids as input and
returns all the information about those episodes.
After taking inputs from the user as multiple id numbers, it doesn't give output as the information about all episodes
let BigBang = {
"_embedded": {
"episodes": [
{
"id": 2913,
"name": "Pilot",
"season": 1,
"number": 1,
"airdate": "2007-09-24",
"airtime": "20:30",
"airstamp": "2007-09-25T00:30:00+00:00",
"runtime": 30,
"_links": {
"self": {
"href": "http:\/\/api.tvmaze.com\/episodes\/2913"
}
}
},
{
"id": 2914,
"name": "The Big Bran Hypothesis",
"season": 1,
"number": 2,
"airdate": "2007-10-01",
"airtime": "20:30",
"airstamp": "2007-10-02T00:30:00+00:00",
"runtime": 30,
"image": {
"medium": "http:\/\/static.tvmaze.com\/uploads\/images\/medium_landscape\/4\/12369.jpg",
"original": "http:\/\/static.tvmaze.com\/uploads\/images\/original_untouched\/4\/12369.jpg"
},
}
let id = prompt('Enter the episode ids');
let Info = (...id) => {
for(let current in BigBang._embedded.episodes) {
if(BigBang._embedded.episodes[current].id === parseInt(id)) {
let Detail = BigBang._embedded.episodes[current];
console.log(Detail);
}
}
}
Info(id);

let str = prompt('Enter the episode ids');
let idArray = JSON.parse("[" + str + "]");
let Info = (ids) => BigBang._embedded.episodes.filter(b => ids.includes(b.id));
console.log(Info(idArray));

After taking inputs from the user as multiple id numbers, it doesn't give output as the information about all episodes
Assuming you need to pass multiple ids, you can use the function filter along with the function indexOf (This is to convert to number and compare, of course, you can map that array first, Etc,. But that part is up to you).
This example receives the ids separated by comma and call the function Infousing the function apply to pass the entered ids as parameters (Like I said this is an example, in real execution you will pass the parameters directly to the function Info).
let BigBang = { "_embedded": { "episodes": [{ "id": 2913, "name": "Pilot", "season": 1, "number": 1, "airdate": "2007-09-24", "airtime": "20:30", "airstamp": "2007-09-25T00:30:00+00:00", "runtime": 30, "_links": { "self": { "href": "http:\/\/api.tvmaze.com\/episodes\/2913" } } }, { "id": 2914, "name": "The Big Bran Hypothesis", "season": 1, "number": 2, "airdate": "2007-10-01", "airtime": "20:30", "airstamp": "2007-10-02T00:30:00+00:00", "runtime": 30, "image": { "medium": "http:\/\/static.tvmaze.com\/uploads\/images\/medium_landscape\/4\/12369.jpg", "original": "http:\/\/static.tvmaze.com\/uploads\/images\/original_untouched\/4\/12369.jpg" }, } ] }};
let id = prompt('Enter the episode ids (separated by comma)');
let Info = (...ids) => {
var episodes = BigBang._embedded.episodes.filter(e => ids.findIndex(i => e.id == +i) !== -1);
console.log(episodes);
}
Info.apply(null, id.split(','));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

Find value of an object in json, node.js

I need a way to find the kills and deaths (etc.) of the corresponding name that is inputted, and if the name is not in the object I need it to output something too.
Something like this:
if (medic does not have(name)) return;
const kills = medic.(name).kills
Sample JSON:
{
"assault": {
"general": {
"kills": 1134,
"deaths": 1122,
"abc": "123"
},
"list": {
"A": {
"name": "name1",
"kills": 12,
"deaths": 120
},
"B": {
"name": "name2",
"kills": 23,
"deaths": 53
}
}
},
"support": {
"general": {
"kills": 123,
"deaths": 11232,
"abc": "11233"
},
"list": {
"A": {
"name": "name4",
"kills": 12,
"deaths": 120
},
"B": {
"name": "name5",
"kills": 23,
"deaths": 53
}
}
}
}
First clean your data to get a nice list of the names and info:
const listOfNames = [...Object.values(data.assault.list), ...Object.values(data.support.list)]
Then use the find method on that list to search for a name, with the backup of "Not Found" if the search returns undefined:
const search = (name) => listOfNames.find(item => item.name===name) || "Not Found"
Then you can use that search function elsewhere:
console.log(search("name2")) gives
See it in action here:
https://repl.it/#LukeStorry/62916291
Do you need assault and support to be sum up or all you need is one of those? Is your data always on the same shape? I'm going to assume that it is, and I'll provide both, the sum and the individual one:
const data = // your JSON here
const getAssaultKills = name => (data.assault.list[name] || {kills: 0}).kills
const getSupportKills = name => (data.support.list[name] || {kills: 0}).kills
const getTotalKills = name =>
getSupportKills(name) + getAssaultKills(name)
getTotalKills("A") // => 24
getTotalKills("C") // => 0

Change Json structure javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How do I change the format of the below json format to expected output:
[
{
"type": "System Usability Score",
"score": 74,
"date": "2020-03-19T18:30:00.000+0000"
},
{
"type": "System Usability Score",
"score": 87,
"date": "2020-03-31T18:30:00.000+0000"
}
]
Expected Output:
[
{
"name": "System Usability Score",
"series": [
{
"name": "2020-03-19T18:30:00.000+0000",
"value": 74
},
{
"name": "2020-03-31T18:30:00.000+0000",
"value": 87
}
]
}
]
Can someone please help?
Try like this with Array.prototype.reduce
"use strict";
const input = [
{
"type": "System Usability Score",
"score": 74,
"date": "2020-03-19T18:30:00.000+0000"
},
{
"type": "Net Promoter Score",
"score": 89,
"date": "2020-03-23T18:30:00.000+0000"
},
{
"type": "Net Promoter Score",
"score": 78,
"date": "2020-03-25T18:30:00.000+0000"
},
{
"type": "System Usability Score",
"score": 87,
"date": "2020-03-31T18:30:00.000+0000"
}
]
var output = input.reduce((collect, {type, score, date}) => {
let el, series
if (el = collect.find(({name}) => name === type)) {
series = el.series
} else {
series = collect[collect.push({name: type, series: []}) - 1].series
}
series.push({name: date, value: score})
return collect
}, [])
console.log(output)

How to sort an array of objects by type? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I want to sort data based on a specific logic.
The rules for ordering are:
Type : Actual.
Type: Projected.
This is my code:
const myData = [{
"id": 1,
"businessEntityId": "BE001",
"financials": {
"Npbt": 2323,
"Interest": 123213,
"Depreciation": 213123,
"Ebit": 1312321,
"EbitDa": 123123,
"Leasing": 123213
},
"type": "Actual",
"startDate": "2018-06-15T00:00:00.000Z",
"endDate": "2018-06-15T00:00:00.000Z",
"model": "Commercial",
"duration": 12,
"quality": "Unqualified"
},
{
"id": 2,
"businessEntityId": "BE002",
"financials": {
"Npbt": 2323,
"Interest": 123213,
"Depreciation": 213123,
"Ebit": 1312321,
"EbitDa": 123123,
"Leasing": 123213
},
"type": "Projected",
"startDate": "2017-06-15T00:00:00.000Z",
"endDate": "2017-06-15T00:00:00.000Z",
"model": "Commercial",
"duration": 12,
"quality": "Projection"
},
{
"id": 3,
"businessEntityId": "BE002",
"financials": {
"Npbt": 2323,
"Interest": 123213,
"Depreciation": 213123,
"Ebit": 1312321,
"EbitDa": 123123,
"Leasing": 123213
},
"type": "Actual",
"startDate": "2017-06-15T00:00:00.000Z",
"endDate": "2017-06-15T00:00:00.000Z",
"model": "Commercial",
"duration": 12,
"quality": "Audited"
}
]
var order = {
model: {
Commercial: 2,
Agribusiness: 1
},
type: {
Historical: 3,
Actual: 2,
Projected: 1,
Proforma: 0
},
Actual: {
Unqualified: 3,
Qualified: 2,
Audited: 1
},
Projected: {
Projection: 3,
Qualified: 2,
Audited: 1
},
BOTTOM: Infinity
};
let result = myData.sort(
(a, b) => {
// eslint-disable-next-line no-unused-expressions
return order.model[a.model] - order.model[b.model] || order.type[a.type] - order.type[b.type]
}
);
console.log(result.map((obj) => obj.id))
So when I run the sort , the result is currently(check console for react app / result):
id 1, id 2, id 3.
I was expecting: 1,3,2?
How can I sort on Type respecting these rules and have type='Projected' at the bottom?

Remove common object from js array and create new js array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have this below JSON array. In this, I want to find the common item object and add it to another list and remove that from the source list.
The item with id is common for two objects. Also, the list is dynamic.
[
{
"id": 1,
"item": {
"id": 1,
"name": "itemA"
}
},
{
"id": 2,
"item": {
"id": 1,
"name": "itemA"
}
},
{
"id": 3,
"item": {
"id": 2,
"name": "itemB"
}
}
]
You could use reduce in combination with a Map for keying your data:
const data = [ { "id": 1, "item": { "id": 1, "name": "itemA" } }, { "id": 2, "item": { "id": 1, "name": "itemA" } }, { "id": 3, "item": { "id": 2, "name": "itemB" } } ];
const [map, dupes] = data.reduce(([map, dupes], obj) =>
map.has(obj.item.id) ? [map, dupes.concat(obj)] : [map.set(obj.item.id, obj), dupes]
, [new Map, []]);
const uniques = [...map.values()];
console.log(uniques);
console.log('dupes:');
console.log(dupes);
After reading your comments, it seems you want to reject anything that has a duplicate, so not even keeping one original. So then the code could be:
const data = [ { "id": 1, "item": { "id": 1, "name": "itemA" } }, { "id": 2, "item": { "id": 1, "name": "itemA" } }, { "id": 3, "item": { "id": 2, "name": "itemB" } } ];
const map = new Map(data.map(obj => [obj.item.id, []]));
data.forEach(obj => map.get(obj.item.id).push(obj));
const uniques = [].concat(...[...map.values()].filter(arr => arr.length === 1));
const dupes = [].concat(...[...map.values()].filter(arr => arr.length > 1));
console.log(uniques);
console.log('dupes:');
console.log(dupes);
Array.reduce over your Array, passing an accumulator.
Accumulator keeps track of found elements.
Check accumulator if iterated element was previously found by id, if yes push it into duplicates.
Otherwise push it into arr.
const arr = [
{
"id": 1,
"item": {
"id": 1,
"name": "itemA"
}
},
{
"id": 2,
"item": {
"id": 1,
"name": "itemA"
}
},
{
"id": 3,
"item": {
"id": 2,
"name": "itemB"
}
}
]
const result = arr.reduce((acc, el, i) => {
if (acc.found[el.item.id]) {
acc.duplicates.push(el)
} else {
acc.source.push(el)
}
acc.found[el.item.id] = true
if (i === arr.length - 1)
delete acc.found
return acc
}, {
source: [],
duplicates: [],
found: {}
})
console.log(result.source) // source with removed duplicates
console.log(result.duplicates) // array of duplicates

Iteration over javascript objects

Write a function that takes Season number and episode number as input
and gives all the information about that particular episode as output
After taking inputs from the user as season number and episode number, it doesn't give output as the information about that particular episode
let BigBang = {
"_embedded": {
"episodes": [
{
"id": 2913,
"name": "Pilot",
"season": 1,
"number": 1,
"airdate": "2007-09-24",
"airtime": "20:30",
"airstamp": "2007-09-25T00:30:00+00:00",
"runtime": 30,
"_links": {
"self": {
"href": "http:\/\/api.tvmaze.com\/episodes\/2913"
}
}
},
{
"id": 2914,
"name": "The Big Bran Hypothesis",
"season": 1,
"number": 2,
"airdate": "2007-10-01",
"airtime": "20:30",
"airstamp": "2007-10-02T00:30:00+00:00",
"runtime": 30,
"image": {
"medium": "http:\/\/static.tvmaze.com\/uploads\/images\/medium_landscape\/4\/12369.jpg",
"original": "http:\/\/static.tvmaze.com\/uploads\/images\/original_untouched\/4\/12369.jpg"
},
}
let season = prompt('Enter Season number');
let number = prompt('Enter Episode number');
let AllInfo = (season,number) => {
for(let current in BigBang._embedded.episodes) {
if(BigBang._embedded.episodes[current].season === season) {
if(BigBang._embedded.episodes[current].number === number) {
let Detail = BigBang._embedded.episodes[current];
alert(Detail);
}
}
}
AllInfo(season,number);
}
Try using .find instead, it'll make the code a lot cleaner:
let BigBang = {
"_embedded": {
"episodes": [{
"id": 2913,
"name": "Pilot",
"season": 1,
"number": 1,
"airdate": "2007-09-24",
"airtime": "20:30",
"airstamp": "2007-09-25T00:30:00+00:00",
"runtime": 30,
"_links": {
"self": {
"href": "http:\/\/api.tvmaze.com\/episodes\/2913"
}
}
},
{
"id": 2914,
"name": "The Big Bran Hypothesis",
"season": 1,
"number": 2,
"airdate": "2007-10-01",
"airtime": "20:30",
"airstamp": "2007-10-02T00:30:00+00:00",
"runtime": 30,
"image": {
"medium": "http:\/\/static.tvmaze.com\/uploads\/images\/medium_landscape\/4\/12369.jpg",
"original": "http:\/\/static.tvmaze.com\/uploads\/images\/original_untouched\/4\/12369.jpg"
},
}
]
}
}
//const inputSeason = prompt('Enter Season number');
const inputSeason = 1;
//const inputNumber = prompt('Enter Episode number');
const inputNumber = 2;
const foundEpisode = BigBang._embedded.episodes.find(({ season, number}) => {
return season === inputSeason && number === inputNumber;
});
if (foundEpisode) console.log(foundEpisode);
else console.log('No matching season/number found!');
You could do that easier with the find() method on your array.
let episode = BigBang._embedded.episodes.find((e) => {
return e.season === season && e.number === number;
});
if (episode) {
alert(episode.name);
}
I have debugged your code and saw that you call AllInfo function within AllInfo .So there is recursive call happen in your code. So remove calling of AllInfo from AllInfo function, your issue will be fixed. Try the following code.
let BigBang = {
"_embedded": {
"episodes": [
{
"id": 2913,
"name": "Pilot",
"season": 1,
"number": 1,
"airdate": "2007-09-24",
"airtime": "20:30",
"airstamp": "2007-09-25T00:30:00+00:00",
"runtime": 30,
"_links": {
"self": {
"href": "http:\/\/api.tvmaze.com\/episodes\/2913"
}
}
},
{
"id": 2914,
"name": "The Big Bran Hypothesis",
"season": 1,
"number": 2,
"airdate": "2007-10-01",
"airtime": "20:30",
"airstamp": "2007-10-02T00:30:00+00:00",
"runtime": 30,
"image": {
"medium": "http:\/\/static.tvmaze.com\/uploads\/images\/medium_landscape\/4\/12369.jpg",
"original": "http:\/\/static.tvmaze.com\/uploads\/images\/original_untouched\/4\/12369.jpg"
},
}]}};
let season = 1;
let number = 2;
let AllInfo = (season,number) => {
for(let current in BigBang._embedded.episodes) {
if(BigBang._embedded.episodes[current].season === season) {
if(BigBang._embedded.episodes[current].number === number) {
let Detail = BigBang._embedded.episodes[current];
alert(JSON.stringify(Detail,null,4));
}
}
}
}
AllInfo(season,number);

Categories