Parse this Json response and loop through the array in JavaScript - javascript

There are many post about this but I can't figure this one out. This is the json response from an Ajax function:
var obj = {
"3901": 10,
"3900": 3,
"3902": 9,
"3899": 2,
"3274": 4,
"3257": 9.5,
"3883": 12,
"3881": "12",
"3876": 3,
"3267": 14,
"3258": 2.5,
"3260": 13.5,
"3259": 6.5,
"3264": 4.5,
"3268": 2,
"3273": 5.5,
"3266": 17,
"3270": 9,
"3271": 8,
"3275": 2,
"3263": 2.5,
"3261": 2.5,
"3265": "37",
"3281": 3,
"3277": 7.5,
"3278": 0.5,
"3276": 7,
"3898": 8,
"3891": 7,
"3293": 1,
"3895": 1,
"3256": 2,
"3903": 10,
"3840": 2,
"3886": 11,
"3884": 8,
"3872": 2,
"3874": 4,
"3284": 1.5,
"3302": 1.25,
"3304": 5,
"3306": 2,
"3329": 1.5,
"3330": 2,
"3333": 6,
"3335": 7.5,
"3327": 1,
"3934": 8,
"3935": 9,
"3939": 1,
"3933": 3,
"3937": 1,
"3322": 3.5,
"3890": 1,
"3878": 5,
"3880": 4,
"3879": 1,
"3889": 2,
"3852": 2,
"3877": 2
}
I have a this of ids: 3902, 3883, 4567 and 3878
All I need is to loop through the those 4 ids and check if those are in the json response and if they are get the value associated to it and if not return 0. For example:
3902 will return 9 and 4567 will return 0
Thanks.

You can put all the ids into an array called ids, then use .map() on that array. For each id within the array, you can look it up in your object using obj[id]. If it doesn't exist, it will return undefined. If this occurs, you can use a default of 0 by using an ||:
See example below:
const obj = {"3901":10,"3900":3,"3902":9,"3899":2,"3274":4,"3257":9.5,"3883":12,"3881":"12","3876":3,"3267":14,"3258":2.5,"3260":13.5,"3259":6.5,"3264":4.5,"3268":2,"3273":5.5,"3266":17,"3270":9,"3271":8,"3275":2,"3263":2.5,"3261":2.5,"3265":"37","3281":3,"3277":7.5,"3278":0.5,"3276":7,"3898":8,"3891":7,"3293":1,"3895":1,"3256":2,"3903":10,"3840":2,"3886":11,"3884":8,"3872":2,"3874":4,"3284":1.5,"3302":1.25,"3304":5,"3306":2,"3329":1.5,"3330":2,"3333":6,"3335":7.5,"3327":1,"3934":8,"3935":9,"3939":1,"3933":3,"3937":1,"3322":3.5,"3890":1,"3878":5,"3880":4,"3879":1,"3889":2,"3852":2,"3877":2};
const ids = [3902, 3883, 4567, 3878];
const res = ids.map(id => obj[id] || 0);
console.log(res);

var jsonObject = {3256: 2, 3257: 9.5, 3258: 2.5, 3259: 6.5, 3260: 13.5, 3261: 2.5, 3263: 2.5, 3264: 4.5, 3265: "37", 3266: 17, 3267: 14, 3268: 2, 3270: 9, 3271: 8, 3273: 5.5, 3274: 4, 3275: 2, 3276: 7, 3277: 7.5, 3278: 0.5, 3281: 3, 3284: 1.5, 3293: 1, 3302: 1.25, 3304: 5, 3306: 2, 3322: 3.5, 3327: 1, 3329: 1.5, 3330: 2, 3333: 6, 3335: 7.5, 3840: 2, 3852: 2, 3872: 2, 3874: 4, 3876: 3, 3877: 2, 3878: 5, 3879: 1, 3880: 4, 3881: "12", 3883: 12, 3884: 8, 3886: 11, 3889: 2, 3890: 1, 3891: 7, 3895: 1, 3898: 8, 3899: 2, 3900: 3, 3901: 10, 3902: 9, 3903: 10, 3933: 3, 3934: 8, 3935: 9, 3937: 1, 3939: 1}
var ids = [3902, 3883, 4567, 3878];
for(var i =0; i < ids.length; i++)
{
if(temp1.hasOwnProperty(ids[i])) //to check propery exist in JSON object
{
console.log(temp1[ids[i]]) //to read value from JSON object
}
}

I think you already have a valid JSON here.
let data = {"3901":10,"3900":3,"3902":9,"3899":2,"3274":4,"3257":9.5,"3883":12,"3881":"12","3876":3,"3267":14,"3258":2.5,"3260":13.5,"3259":6.5,"3264":4.5,"3268":2,"3273":5.5,"3266":17,"3270":9,"3271":8,"3275":2,"3263":2.5,"3261":2.5,"3265":"37","3281":3,"3277":7.5,"3278":0.5,"3276":7,"3898":8,"3891":7,"3293":1,"3895":1,"3256":2,"3903":10,"3840":2,"3886":11,"3884":8,"3872":2,"3874":4,"3284":1.5,"3302":1.25,"3304":5,"3306":2,"3329":1.5,"3330":2,"3333":6,"3335":7.5,"3327":1,"3934":8,"3935":9,"3939":1,"3933":3,"3937":1,"3322":3.5,"3890":1,"3878":5,"3880":4,"3879":1,"3889":2,"3852":2,"3877":2};
let arr = [3902, 3883, 4567 , 3878];
let ans = arr.map( i => {
if(data[i] === undefined) {
console.log(0);
return 0;
}
else {
console.log(data[i]);
return data[i];
}
});
ans is the required array .

You can use a foreach
j={"3901":10,"3900":3,"3902":9,"3899":2,"3274":4,"3257":9.5,"3883":12,"3881":"12","3876":3,"3267":14,"3258":2.5,"3260":13.5,"3259":6.5,"3264":4.5,"3268":2,"3273":5.5,"3266":17,"3270":9,"3271":8,"3275":2,"3263":2.5,"3261":2.5,"3265":"37","3281":3,"3277":7.5,"3278":0.5,"3276":7,"3898":8,"3891":7,"3293":1,"3895":1,"3256":2,"3903":10,"3840":2,"3886":11,"3884":8,"3872":2,"3874":4,"3284":1.5,"3302":1.25,"3304":5,"3306":2,"3329":1.5,"3330":2,"3333":6,"3335":7.5,"3327":1,"3934":8,"3935":9,"3939":1,"3933":3,"3937":1,"3322":3.5,"3890":1,"3878":5,"3880":4,"3879":1,"3889":2,"3852":2,"3877":2}
se=[3902, 3883, 4567 , 3878]
res=[]
se.forEach(s=>{
res.push({[s]:j[s]||0})
})
console.log(res)

Related

Splitting an array into 3 unequal arrays in JavaScript

Suppose I have an array of
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
And I want to split it in 3, with two arrays containing the first and last X elements of the original array, and the third array containing the remaining elements, like so:
#1 - [0, 1, 2]
#2 - [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
#3 - [13, 14, 15]
Is there a shorter/better way of doing that instead of:
const splitBy = 3;
const originalArray = Array.from(Array(16).keys());
const result = [
originalArray.slice(0, splitBy),
originalArray.slice(splitBy, -splitBy),
originalArray.slice(-splitBy),
];
console.log(result)
"better" is subjective... however, if you need this more than once, a generic function could be an option:
function multiSlice(a, ...slices) {
let res = [], i = 0
for (let s of slices) {
res.push(a.slice(i, s))
i = s
}
res.push(a.slice(i))
return res
}
// for example,
const originalArray = Array.from(Array(16).keys());
console.log(multiSlice(originalArray, 3, -3))
console.log(multiSlice(originalArray, 2, 5, 10, 12))

To find match element in array json.file and change it [node js]

Good afternoon, I have a script that changes the value of the json file
const fsp = require('fs').promises;
async function udpateTimeInFile() {
try {
let data = await fsp.readFile('example.json');
let obj = JSON.parse(data);
obj.number = 777;
await fsp.writeFile('example.json', JSON.stringify(obj));
} catch(e) {
console.log(e);
}
}
udpateTimeInFile();
I need the script to find the first number 2 in the array and object numbers and change the unit to 3
and my json
{
"foods": 111,
"numbers": [1, 27, 5, 7, 0, 0, 2, 0, 0],
"surnames": [1, 1, 1, 1, 1, 1, 1, 1, 1],
"date": 0
}
And after execution js application the file would become like this
{
"foods": 111,
"numbers": [1, 27, 5, 7, 0, 0, 3, 0, 0],
"surnames": [1, 1, 1, 1, 1, 1, 1, 1, 1],
"date": 0
}
You can use the Array#findIndex method to find the index of the first occurrence of 2, then you can use the index to change the value to 3.
DEMO
const obj = {
"foods": 111,
"numbers": [1, 27, 5, 7, 0, 0, 2, 0, 0],
"surnames": [1, 1, 1, 1, 1, 1, 1, 1, 1],
"date": 0
},
i = obj.numbers.findIndex(num => num === 2);
if (i > -1) {
obj.numbers[i] = 3;
}
console.log( obj );

Getting a "not defined" error in my JavaScript code when I think it is defined

I am working on a project for SkillCrush and am getting a "not defined" error, when I feel as though I've defined the variable at the top of the code. I 100% know I'm doing something wrong, but not sure what. Any suggestions?
var createPolitician = function (name)
{
var politician = {}; //is this not defined here?
politician.name = name;
politician.electionResults = null;
politician.totalVotes = 0;
return politician;
};
var oscar = createPolitician("Oscar Jiminez");
var luke = createPolitician("Luke Spencer");
oscar.electionResults = [5, 1, 7, 2, 33, 6, 4, 2, 1, 14, 8, 3, 1, 11, 11, 0, 5, 3, 3, 3, 7, 4, 8, 9, 3, 7, 2, 2, 4, 2, 8, 3, 15, 15, 2, 12, 0, 4, 13, 1, 3, 2, 8, 21, 3, 2, 11, 1, 3, 7, 2];
luke.electionResults = [4, 2, 4, 4, 22, 3, 3, 1, 2, 15, 8, 1, 3, 9, 0, 6, 1, 5, 5, 1, 3, 7, 8, 1, 3, 3, 1, 3, 2, 2, 6, 2, 14, 0, 1, 6, 7, 3, 7, 3, 6, 1, 3, 17, 3, 1, 2, 11, 2, 3, 1];
oscar.electionResults[9] = 1;
luke.electionResults[9] = 28;
oscar.electionResults[4] = 17;
luke.electionResults[4] = 38;
oscar.electionResults[43] = 11;
luke.electionResults[43] = 27;
console.log(oscar.electionResults);
console.log(luke.electionResults);
politician.countTotalVotes = function()
{
this.totalVotes = 0;
for (var i = 0; i < this.electionResults.length; i++);
{
this.totalVotes = this.totalVotes + this.electionResults[i];
}
}
oscar.countTotalVotes();
luke.countTotalVotes();
console.log(oscar.totalVotes);
console.log(luke.totalVotes);
Error:
"error"
"ReferenceError: politician is not defined
at reloyur.js:32:1"
politician.countTotalVotes = ...
That won't work as politician only exists while you create luke or oscar (it then points to one of them). Instead you could do:
luke.countTotalVotes = oscar.countTotalVotes = function() { /*...* };
But for more politicians that gets a bit complicated. You could however just make a function that you pass a politician into:
function countTotalVotes(politician) {
//...
}
countTotalVotes(luke);
Or you use the power of inheritance.
As I suggested in comments, you can rewrite Politician as a class, which basically gives you a template for reusable functionality. If you're not familiar with the concept, a good google term would be "prototypal inheritance" for follow-up on the subject in general. For now, here's a rewrite of your script using a class:
class Politician {
constructor (name) {
this.name = name;
this.electionResults = [];
}
// no need to even write a .countTotalVotes() method
// just define .totalVotes as a getter that does the work
get totalVotes () {
var total = 0;
for (var i = 0; i < this.electionResults.length; i++) {
total += this.electionResults[i];
}
return total;
}
}
var oscar = new Politician("Oscar Jiminez");
var luke = new Politician("Luke Spencer");
oscar.electionResults = [5, 1, 7, 2, 33, 6, 4, 2, 1, 14, 8, 3, 1, 11, 11, 0, 5, 3, 3, 3, 7, 4, 8, 9, 3, 7, 2, 2, 4, 2, 8, 3, 15, 15, 2, 12, 0, 4, 13, 1, 3, 2, 8, 21, 3, 2, 11, 1, 3, 7, 2];
luke.electionResults = [4, 2, 4, 4, 22, 3, 3, 1, 2, 15, 8, 1, 3, 9, 0, 6, 1, 5, 5, 1, 3, 7, 8, 1, 3, 3, 1, 3, 2, 2, 6, 2, 14, 0, 1, 6, 7, 3, 7, 3, 6, 1, 3, 17, 3, 1, 2, 11, 2, 3, 1];
oscar.electionResults[9] = 1;
luke.electionResults[9] = 28;
oscar.electionResults[4] = 17;
luke.electionResults[4] = 38;
oscar.electionResults[43] = 11;
luke.electionResults[43] = 27;
// console.log(oscar.electionResults);
// console.log(luke.electionResults);
// these are no longer required
// oscar.countTotalVotes();
// luke.countTotalVotes();
console.log(oscar.name, 'has', oscar.totalVotes, 'votes');
console.log(luke.name, 'has', luke.totalVotes, 'votes');
Move your countTotalVotes function into your create function:
var createPolitician = function (name)
{
var politician = {};
politician.name = name;
// set to an empty array so this is defined
politician.electionResults = [];
politician.totalVotes = 0;
// here politician exists, add a function to the object that you can call later
politician.countTotalVotes = function()
{
this.totalVotes = 0;
for (var i = 0; i < this.electionResults.length; i++)
{
this.totalVotes = this.totalVotes + this.electionResults[i];
}
}
return politician;
};
I corrected your mistakes in your code. You could change your code like follows:
function createPolitician(name)
{
var politician =
{
name: name,
electionResults: null,
totalVotes: 0,
countTotalVotes: function()
{
//this.totalVotes = 0; <- irrelevant because you use it only one time
for(var i = 0; i < this.electionResults.length; i++)//";" symbol on the end is your mistake too
{
this.totalVotes += this.electionResults[i];
}
}
};
return politician;
};
var oscar = createPolitician("Oscar Jiminez");
var luke = createPolitician("Luke Spencer");
oscar.electionResults = [5, 1, 7, 2, 33, 6, 4, 2, 1, 14, 8, 3, 1, 11, 11, 0, 5, 3, 3, 3, 7, 4, 8, 9, 3, 7, 2, 2, 4, 2, 8, 3, 15, 15, 2, 12, 0, 4, 13, 1, 3, 2, 8, 21, 3, 2, 11, 1, 3, 7, 2];
luke.electionResults = [4, 2, 4, 4, 22, 3, 3, 1, 2, 15, 8, 1, 3, 9, 0, 6, 1, 5, 5, 1, 3, 7, 8, 1, 3, 3, 1, 3, 2, 2, 6, 2, 14, 0, 1, 6, 7, 3, 7, 3, 6, 1, 3, 17, 3, 1, 2, 11, 2, 3, 1];
oscar.electionResults[9] = 1;
luke.electionResults[9] = 28;
oscar.electionResults[4] = 17;
luke.electionResults[4] = 38;
oscar.electionResults[43] = 11;
luke.electionResults[43] = 27;
console.log(oscar.electionResults);
console.log(luke.electionResults);
oscar.countTotalVotes();
luke.countTotalVotes();
console.log(oscar.name, 'has', oscar.totalVotes, 'votes');
console.log(luke.name, 'has', luke.totalVotes, 'votes');
The error message should be accompanied with a line and column number. In this case, the error is occurring on line 32:
politician.countTotalVotes = function()
In the definition of the createPolitician function, you declared a variable named politician. var creates a variable that lives within the function it was declared in. If it is not inside of a function, it creates a global variable.
You left the function the variable was declared in, and thus it isn't usable anymore.
If you think about it, it'd be very ambiguous if you could re-use that politician variable later on. What would it refer to?
If you want to be able to call countTotalVotes() on the politicians, then Patrick's comment about using a Class is a good approach to take. You could also assign the function to the politician object that you return from createPolitician - this would give each instance of the politician its own copy of the function.
It's all about variable scope. Declare the politician object variable outside of the createPolitician function for you to access out of the function. It cannot be accessed out of its scope that is why you get an undefined error.

Return ONLY one iteration of a pattern in an array in Javascript

I'm trying to find and return a pattern (made up of numbers) in an array, but only return the pattern once.
ex. findPattern([1, 2, 3, 4, 5]);
should return [1]; not [1,1,1,1];
ex2. findPattern([1, 5, 4, 8, 7, 11, 10, 14, 13]);
should return ([4, -1]); not [ 4, -1, 4, -1, 4, -1, 4, -1 ];
ex3. findPattern([1, 5, 2, 3, 1, 5, 2, 3, 1]);
should return [ 4, -3, 1, -2, ]; not [ 4, -3, 1, -2, 4, -3, 1, -2 ];
Any thoughts on how I could do this simply, with a function findPattern(arr){}?
It appears that you want to remove duplicates from an array. You can leverage the Set class to make a function like so:
const unique = xs => [ ...new Set(xs) ];
Then to use:
unique(findPattern([ 1, 2, 3, 4, 5 ])); // [ 1 ]
More information about Set is available on MDN.

Add new items and slice from the top Javascript

I have a list with items like:
var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...];
I want, for every scroll, to add 15th new items and then to slice from the top another 15th elements.
Can you help me? Thanks!!!
Updated:
getMoreItems(items: any) {
var lastIndex: number;
if (items.visible.length) {
var lastItem: any = _.last(items.visible);
lastIndex = _.findLastIndex(items.allValues, { Name: lastItem.Name });
}
var startIndex = lastIndex + 1 || 0;
var endIndex = Math.min(startIndex + 15, items.allValues.length);
var newItems = items.allValues.slice(startIndex, endIndex);
if (items.visible.length > 30) {
items.visible = items.visible.slice(0, 15).concat(newItems);
} else {
items.visible = items.visible.concat(newItems);
}
}
var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...];
values = values.splice(0,15); // remove first 15 items
values = values.concat([another 15 items]); // add next 15
And of course you can inline this:
values = values.splice(0,15).concat([x1...x2])
Something like this?
var numbers = [1,2,3,4,5,6,7,8,9,10];
numbers = numbers.slice(2).concat([11,12]);
console.log(numbers);
>> [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
if you have array on scroll you can reinitialize your array:
var old= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
scroll=[32, 232,23, 232, 23, 232, 23,238, 92, 120];
old=scroll;
console.log(old);
and if you ahve items one by one then you can use pattern:
if you have array on scroll you can reinitialize your array:
var old= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
old.push(next_value);
old.shift()
console.log(old);

Categories