I am a bit stuck, I need a way to make sure all the lines contain "new" in the status or otherwise return false,
var found = data.Lines.find(function(line) {
if (line.status.some(({
status
}) => status !== "new")) {
return false;
}
});
See example http://jsfiddle.net/sucL9rnm/10/
Data
var data = {
"id": 1,
"Lines": [{
"id": 111,
"status": [{
"status": "new"
}]
},
{
"id": 111,
"status": [{
"status": "new"
}]
},
{
"id": 111,
"status": [{
"status": "new"
}]
}
]
}
I gotchu man. Here's a simple solution with a for-loop:
function isFound() {
for (var i = 0; i < data.Lines.length; i++)
if (data.Lines[i].status[0].status !== 'new')
return false;
return true;
}
JSFiddle: http://jsfiddle.net/sucL9rnm/24
This function will return true only if all nested elements of data.lines have the "new" status attribute. Give it a try. Let me know if you have any additional questions.
Here is a possible solution :
var data = {
"id": 1,
"Lines": [{
"id": 111,
"status": [{
"status": "new"
}]
},
{
"id": 111,
"status": [{
"status": "new"
}]
},
{
"id": 111,
"status": [{
"status": "new"
}]
}
]
}
console.log(data.Lines.every(d => d.status[0].status === 'new'));
Using .map and .filter:
data.Lines.filter(line => {
return line.status && line.status.map(item => item.status)
.filter(status => status == 'new')
.length == 0
})
.length > 0
This solution takes into account that data.Lines may have a status with more than one object in it.
Just an approach using short IF and filter
(data.Lines.filter(o=>{
return o.status[0].status !='new';
}).length)?console.log(false):console.log(true)
With status length more than 0:
(data.Lines.filter(o=>{
return o.status.filter(o2=>{
return o2.status !='new';
}).length
}).length)?console.log(false):console.log(true)
Here a non-standard approach, the advantage, is not necessary to know exactly how the object is.
(data.Lines.length == JSON.stringify(data).match(/new/g).length)?console.log(true):console.log(false);
Related
I have an array of objects like this one:
let arr1 = [{
"ref": 1,
"index": "300",
"data": {
"id": 10,
"status": {
"code": "red"
}
}
}, {
"ref": 2,
"index": "301",
"data": {
"id": 20,
"status": {
"code": "blue"
}
}
}];
I want to replace the status.code by the one given in this other array of objects:
let arr2 = [{
"id": 10,
"content": {
"name": "green"
}
}, {
"id": 20,
"content": {
"name": "yellow"
}
}];
My idea is to map the first array and the use the find function (or filter) to loop the second array and when the ID's match change the values but I'm missing something, how can i do this the most optimized for performance and readability way?
let res: any[];
res = arr2.map((x: any) =>
arr1.find((y: any) =>
(y.data.id === x.id) ? 'logic if match' : 'return'
));
I would first change the format of arr2 in such a way that it is easier to access in such a format: (If you can easily change how you get this data, it would be better I think. Otherwise, transform the data as below.)
const idStatusCodeMap = {
"10": "green",
"20": "yellow"
}
We do this so we can just look if there is idStatusCodeMap[10] or idStatusCodeMap[anyId]. This makes it possible that you only loop through arr1, not a nested loop for both arr1 and arr2.
Then, loop through arr1 and replace the colours if necessary. If suppose, a new colour is not found on idStatusCodeMap, such as for id = 30, then don't do anything for that.
let arr1 = [{
"ref": 1,
"index": "300",
"data": {
"id": 10,
"status": {
"code": "red"
}
}
}, {
"ref": 2,
"index": "301",
"data": {
"id": 20,
"status": {
"code": "blue"
}
}
}];
let arr2 = [{
"id": 10,
"content": {
"name": "green"
}
}, {
"id": 20,
"content": {
"name": "yellow"
}
}];
let idStatusCodeMap = {}
//transpiling arr2 to more performant hashMap
arr2.forEach(item => {
idStatusCodeMap[item.id] = item.content.name;
})
console.log(idStatusCodeMap);
arr1 = arr1.map(item => {
//if the id of an item in arr1 is found in code map, replace it with new value.
//if not found, it will skip.
if(idStatusCodeMap[item.data.id]) {
item.data.status.code = idStatusCodeMap[item.data.id]
}
return item;
})
console.log(arr1);
I need select ony on field to services, look:
async find(): Promise<AccountEntity[]> {
const result = await this.repository
.createQueryBuilder("account")
.select(['account', 'accountServices', 'service.description'])
.leftJoinAndSelect("account.accountAndServices", "accountServices")
.leftJoinAndSelect("accountServices.service", "service")
.getMany();
return result === undefined ? null : result;
}
How to ? please.
I don't want null attributes to appear and I also want to choose which attributes to show
I need :
{
"message": "",
"success": true,
"data": [
{
"id": 1,
"name": "STONES TECNOLOGIA LTDA",
"accountAndServices": [
{
"service": {
"name": "Construção de uma casa",
},
"date_initial": "2021-08-01T07:39:18.000Z",
"date_final": "2021-08-01T07:39:20.000Z",
"value": "10.00",
"created_by": 1,
"is_active": true,
"id": 1,
"pay_day": 10,
"nfse": 0,
"created_at": "2021-08-01T07:39:27.000Z",
},
{
"service": {
"name": "Desenvolvimento de sistemas",
},
"date_initial": "2021-08-01T07:40:01.000Z",
"date_final": "2021-08-01T07:40:02.000Z",
"value": "20.00",
"created_by": 1,
"is_active": true,
"id": 2,
"pay_day": 20,
"nfse": 0,
"created_at": "2021-08-01T07:40:11.000Z",
}
]
}
],
"errors": null
}
I Need selection only field on entity join.
Select with innerJoin you must use addSelect(...).
The find function must not manipulate any data and should return an array of AccountEntity (empty if not found):
function find(): Promise<AccountEntity[]> {
return this.repository
.createQueryBuilder("a")
.innerJoin("account.accountAndServices", "as")
.innerJoin("accountServices.service", "s")
.select(['a.id', 'a.name', 'a.status'])
.addSelect(['as.date_initial', 'as.date_final', 'as.service_id', 'as.value', 'as.nfse', 'as.value', 'as.created_by', 'is_active', 'pay_day', 'created_at'])
.addSelect(['s.name'])
.getMany();
}
Note that to obtain the result from the function you must use await.
Moreover, surround it with try and catch for a better error handling.
Example:
try {
const accounts: AccountEntity[] = await find();
} catch(error) {
console.error(`Error: ${error}`);
}
To transform the array of AccountEntity to another object:
function transform(accounts?: AccountEntity[]) {
return {
message: "",
success: accounts !== undefined,
data: accounts,
errors: null
};
}
Lets say i have 2 Json responses from a server, one of which is 30 seconds older that the new one. How would i be able to check if an object is still inside the response and after testing if it is still there update an object in another json file to add +1 to the number of that object.
(an example because i can´t explain)
JSON coming in
"names and id´s in json changed"
{
"description": "Insert description here;",
"favicon": null,
"latency": 78.085,
"players": {
"max": 20,
"online": 3,
"sample": [
{
"id": "07bda75d-d8d2-4108-94a7-ba2c09127nsj",
"name": "oajhebskaa"
},
{
"id": "8d8aac43-112b-402b-8771-67b49183lazf",
"name": "jahebianl"
},
{
"id": "67d8a66b-ce37-439f-9020-e6de827dn2o9",
"name": "ffwqehas"
}
]
},
"version": {
"name": "Paper 1.16.4",
"protocol": 754
}
}
After cutting out wanted values it looks like this :
[
'07bda75d-d8d2-4108-94a7-ba2c09127nsj',
'8d8aac43-112b-402b-8771-67b49183lazf',
'67d8a66b-ce37-439f-9020-e6de827dn2o9'
]
What i want to do
Now upon a new response coming in i want to update another json file which should idealy look something like this...
{
"players" : [
{ "07bda75d-d8d2-4108-94a7-ba2c09127nsj": "0" },
{ "8d8aac43-112b-402b-8771-67b49183lazf": "0" },
{ "67d8a66b-ce37-439f-9020-e6de827dn2o9": "0" }
]
}
...and add 1 to the number behind a the certain playerid.
Something like this should work.
let samplePayload = {
"description": "Insert description here;",
"favicon": null,
"latency": 78.085,
"players": {
"max": 20,
"online": 3,
"sample": [{
"id": "07bda75d-d8d2-4108-94a7-ba2c09127nsj",
"name": "oajhebskaa"
},
{
"id": "8d8aac43-112b-402b-8771-67b49183lazf",
"name": "jahebianl"
},
{
"id": "67d8a66b-ce37-439f-9020-e6de827dn2o9",
"name": "ffwqehas"
}
]
},
"version": {
"name": "Paper 1.16.4",
"protocol": 754
}
};
let previousResponseIds = [];
let trackingObj = {};
function responseMiddleware(payload) {
let responseIds = payload.players.sample.map(v => v.id);
let matches = previousResponseIds.filter(v => responseIds.find(x => x === v));
for (let i = 0; i < matches.length; i++) {
if (trackingObj.hasOwnProperty(matches[i])) trackingObj[matches[i]] += 1;
else trackingObj[matches[i]] = 0;
}
previousResponseIds = responseIds;
}
/*UI below*/
let pre = document.getElementsByTagName('pre')[0];
(function updateUI() {
pre.innerText = JSON.stringify(trackingObj, null, 1);
setTimeout(updateUI, 200);
})();
document.getElementById("AddResponse").addEventListener("click", function() {
responseMiddleware(samplePayload);
});
<strong>trackingObj:</strong>
<pre></pre>
<button id="AddResponse">Simulate Response</button>
Let's start with
{
"players" : [
{ "07bda75d-d8d2-4108-94a7-ba2c09127nsj": "0" },
{ "8d8aac43-112b-402b-8771-67b49183lazf": "0" },
{ "67d8a66b-ce37-439f-9020-e6de827dn2o9": "0" }
]
}
let mainObj = JSON.parse(response1);
let players = JSON.parse(response2);
for (let entry of mainObj.players.sample) {
if (players.players.indexOf(entry.id) > -1) {
players.players[entry.id]++;
}
}
I don't have a chance to test it right this moment, give it a shot, and it should put you on the right track.
I am new to react and javascript. Here I am trying to use the lodsh function.
I have an array of object which looks like ,
const data = [{
"Id": "1",
"testone": 100,
"test": 40,
"Original": {
"Id": "11"
},
"__Parent__": {
"Id": "20",
"Status": "INP"
}
}, {
"Id": "2",
"testone": 120,
"test": 20,
"Original": {
"Id": "10"
},
"__Parent__": {
"Id": "21",
"Status": "Book"
}
},{
"Id": "3",
"testone": 110,
"test": 140,
"Original": {
"Id": "11"
},
"__Parent__": {
"Id": "20",
"Status": "INP"
}
}, {
"Id": "4",
"testone": 100,
"test": 40,
"Original": {
"Id": "11"
},
"__Parent__": {
"Id": "20",
"Status": "Val"
}
}]
Here, I have one function which has the product Id . which I am passing from another function =>
cont value = (PID, data) => {
}
So, this function ,
I need do sum , where first I need to take all the object which has the same Id as PID. The Id from object is to be Original.ID. If these matches then after that ,I need to check the status of that objects like , is status is either INP or BOOK then for summation need to take the
testone key value or else need to take the `test` key value.
So, In the given example it will be like ,
Id is 11 which is passed to a function and in the given object 3 objects where it matches.
Now,
while returning sum it will be like ,
100 + 100 + 40 which will be 240.
So, How do I do this . thanks .
I think it's best to do it with Array.reduce if you support IE9 and after.
const sum = data.reduce((total, item) => {
if (item.Original.Id !== PID) return total;
const { status, testone, test } = item;
let addition = 0;
if (status === "INP") addition = testone;
else if (status === "BOOK") addition = test;
return total + addition;
}, 0);
I would like to how to get the value based on input objects in javascript.
If the source matches the currency and also matches the type in paymentin and paymentout in object then get the value of speed and fees
for example 'SGD' with type_in 'credit' and type_out 'bank' should return the speed and fee
Expected Output:
id: transfer credit: 1 days 1% pay_in: pay_out: bank
id: insta debit: 1 days 1.5% pay_in: pay_out: bank
I tried but i got stuck
function getValue(source,typein,typeout,obj){
var filterArr = source.filter(function(value){
return value.country_from.filter(function(payin){
const in= payin.paymentIn.filter(function(ty){
return ty.type == typein
})
const out = payin.paymentIn.filter(function(ty){
return ty.type == typeout
})
})
})
}
var result = getValue(source,type_in,type_out,obj);
//input objects
var source="SGD";
var type_in="credit";
var type_out="bank";
var obj = [{
"id": "transfer",
"country_from": [{
"currency": [
"SGD",
"USD"
],
"paymentIn": [{
"type": "credit",
"speed": {
"unit": "days",
"number": "1"
},
"fee": {
"type": "%",
"number": "1"
}
}],
"paymentOut": [{
"type": "bank",
"speed": {
"unit": "days",
"number": "2"
}
}]
}]
}, {
"id": "insta",
"country_from": [{
"currency": [
"SGD",
"USD"
],
"paymentIn": [{
"type": "credit",
"speed": {
"unit": "days",
"number": "1"
},
"fee": {
"type": "%",
"number": "1.5"
}
}],
"paymentOut": [{
"type": "bank",
"speed": {
"unit": "days",
"number": "2"
}
}]
}]
}]
I think you have made some mistakes on your initial code, but I guess it is due to the confusion of dealing with so many layers of objects and arrays. This is what you should do:
const getValue = (source, typein, typeout, obj) => {
const res = obj.map(item => {
if (item['country_from'][0]['paymentIn'][0]['type'] === typein
&& item['country_from'][0]['currency'].includes(source)
&& item['country_from'][0]['paymentOut'][0]['type'] === typeout) {
return `id: ${item['id']} credit: ${item['country_from'][0]['paymentIn'][0]['speed']['number']} days credit: ${item['country_from'][0]['paymentIn'][0]['fee']['number']}${item['country_from'][0]['paymentIn'][0]['fee']['type']} pay_in: pay_out: ${item['country_from'][0]['paymentOut'][0]['speed']['number']}`
}
});
return res;
}
getValue('SGD', 'credit', 'bank', obj);
Basically, I will iterate through every element of the input array, obj (which is the one you posted on your question), and within each iteration, I check for the following 3 conditions using the if statement.
1) The paymentIn type matches typein
2) The paymentOut type matches typein
3) currency contains source
Elements that fulfil the above 3 conditions will the string result.
EDIT: To answer your question on the comments, if the paymentIn array has more than one object, we can use Array.some() to check if the object with the type property has the same value as typeIn.
if (item['country_from'][0]['paymentIn'].some(payment => payment['type']===typein)
&& item['country_from'][0]['currency'].includes(source)
&& item['country_from'][0]['paymentOut'][0]['type'] === typeout) {
// to get the object with that typein
const filteredPaymentIn = item['country_from'][0]['paymentIn'].filter(payment => payment['type']===typein)[0];
}