Invert boolean Values in JS object array [closed] - javascript

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 3 days ago.
This post was edited and submitted for review 3 days ago.
Improve this question
I'm dealing with object array
var data = [
{
"rdd": "Transducer Failure",
"performance": true,
"agc": true,
"snr": true,
"sos": true,
"flowvel": true
},
{
"rdd": "Detection Problem",
"performance": false,
"agc": false,
"snr": false,
"sos": false,
"flowvel": false
},
{
"rdd": "Ultrasonic Noise",
"performance": false,
"agc": false,
"snr": false,
"sos": false,
"flowvel": false
},
{
"rdd": "Process Condition Pressure",
"performance": false,
"agc": false,
"snr": false,
"sos": false,
"flowvel": false
},
{
"rdd": "Process Condition Temperature",
"performance": false,
"agc": true,
"snr": false,
"sos": true,
"flowvel": false
},
{
"rdd": "Fouling",
"performance": false,
"agc": false,
"snr": false,
"sos": false,
"flowvel": false
},
{
"rdd": "Changes in flow profile",
"performance": false,
"agc": false,
"snr": false,
"sos": false,
"flowvel": false
},
{
"rdd": "High Velocity",
"performance": true,
"agc": true,
"snr": true,
"sos": false,
"flowvel": false
}
]
Now I want to invert value of object, whichever is false make true and vice verse. also, need to extract key's whose value is True after inversion .. I tried couple of things but no luck.
any idea ??
EDIT :
I Tried using
console.log(data);
for (var key in data) {
var obj = data[key];
Object.entries(obj).forEach(([key, value]) => {
if(value == false){
value = true;
}
})
}
console.log(data)
result remains same

You could check the type of value and get the negated value or value of not boolean.
const
data = [{ rdd: "Transducer Failure", performance: true, agc: true, snr: true, sos: true, flowvel: true }, { rdd: "Detection Problem", performance: false, agc: false, snr: false, sos: false, flowvel: false }, { rdd: "Ultrasonic Noise", performance: false, agc: false, snr: false, sos: false, flowvel: false }, { rdd: "Process Condition Pressure", performance: false, agc: false, snr: false, sos: false, flowvel: false }, { rdd: "Process Condition Temperature", performance: false, agc: true, snr: false, sos: true, flowvel: false }, { rdd: "Fouling", performance: false, agc: false, snr: false, sos: false, flowvel: false }, { rdd: "Changes in flow profile", performance: false, agc: false, snr: false, sos: false, flowvel: false }, { rdd: "High Velocity", performance: true, agc: true, snr: true, sos: false, flowvel: false }],
result = data.map(o => Object.fromEntries(Object
.entries(o)
.map(([k, v]) => [k, typeof v === 'boolean' ? !v : v])
));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

How to dynamically load UI elements from JSON object based on user inputs, where some JSON object has false/true which should not be loaded?

{ country : "United Kingdom" ,
format : {
recipient_name: true,
business_name: true,
post_office_box:false,
rural_route_identifier:false,
station_informaton:false,
suite_apartment_number: true,
street_address:{
street_name: true,
building_number: true,
building_name: true
},
street_address2 : false,
quarter_area: false,
neighborhood : false,
city_provinceCode : false,
postal_code: true,
city_town_locality: true,
locality_name: true,
municipality_name:false,
state: false,
province: false,
additional_information:true
},
coordi: {
Lat
Longi
}
}

accumalator in reduce function either empty or not having the array data

Followin is the array which i wanna reduce
[{
"CIs": {
"CIs": {
"x1": false,
"x2": true,
"x5": false,
"x3": true,
"x4": true,
},
"Username": "dev1"
}
},
​
{
"CIs": {
"CIs": {
"x3": true,
"x2": true,
"x1": false,
"x4": true,
"x5": true
},
"Username": "dev1"
}
},,
​
{
"CIs": {
"CIs": {
"x3": true,
"x2": true,
"x1": false,
"x4": true,
"x5": true
},
"Username": "dev2"
}
}
]
Here we c the "Username:dev1" that twice (these objects can be N no. of times) which I wanna reduce to the
i.e., resultant array
[{
"CIs": {
"CIs": {
"x3": true,
"x2": true,
"x1": false,
"x4": true,
"x5": true
},
"Username": "dev1"
}
},,
​
{
"CIs": {
"CIs": {
"x3": true,
"x2": true,
"x1": false,
"x4": true,
"x5": true
},
"Username": "dev2"
}
}
]
the issue is when I use reduce function and console "acc" then
Case 1: // there the acc is [] empty array
reduceRes=upl.reduce(function(acc,d){
console.log("acc,d",acc,d)
//some logic here
return acc;},[])}
Case 2: // there the acc is first object i.e., "{ "CIs": { "CIs": { "x1": false, "x2": true, "x5": false, "x3": true, "x4": true, }, "Username": "dev1" }"
reduceRes=upl.reduce(function(acc,d){
console.log("acc,d",acc,d)
//some logic here
return acc;})}
"acc" must be an array of 3 objects
I'm not following as to why "acc" is not an array of 3 objects
Can anyone lemme know as to where I'm going wrong

using .join() based on condition in Javascript

I am trying to loop through the components array and join all the tire component descriptions with a comma (, ) if there are multiple.
let dataForTemplate = {};
incident = {
complaint_id: 55556473,
components: [{
component_id: 263,
name: 'SEAT BELTS',
description: '150000 SEAT BELTS',
is_public: true,
is_vehicle: true,
is_equipment: false,
is_tire: false,
is_child_seat: false,
is_active: true,
is_deleted: false,
risk_matrix_default_id: 1
},
{
component_id: 300,
name: 'TIRES',
description: '190000 TIRES',
is_public: true,
is_vehicle: true,
is_equipment: false,
is_tire: true,
is_child_seat: false,
is_active: true,
is_deleted: false,
risk_matrix_default_id: 17
},
{
component_id: 1025,
name: 'CHILD SEAT:VEHICLE TETHER ANCHOR',
description: '532000 CHILD SEAT:VEHICLE TETHER ANCHOR',
is_public: true,
is_vehicle: false,
is_equipment: false,
is_tire: false,
is_child_seat: true,
is_active: true,
is_deleted: false,
risk_matrix_default_id: 4
}
]
};
Here is what I am trying:
if (incident.components && incident.components.length > 0) {
dataForTemplate.tire_components = incident.components.map((e) => {
console.log(e);
if (e.is_tire) {
return ${e.description};
}
}).join(' ,');
}
console.log(dataForTemplate);
Current output: {tire_components: " ,190000 TIRES ,"}
Expected output: {tire_components: "190000 TIRES"}
It should only join string with comma if there are multiple descriptions satisfying the condition.
Filter the array to get the is_tire entries, map tehm to get the description and join the result :
let dataForTemplate = {};
incident = {
complaint_id: 55556473,
components: [
{
component_id: 263,
name: "SEAT BELTS",
description: "150000 SEAT BELTS",
is_public: true,
is_vehicle: true,
is_equipment: false,
is_tire: false,
is_child_seat: false,
is_active: true,
is_deleted: false,
risk_matrix_default_id: 1
},
{
component_id: 300,
name: "TIRES",
description: "190000 TIRES",
is_public: true,
is_vehicle: true,
is_equipment: false,
is_tire: true,
is_child_seat: false,
is_active: true,
is_deleted: false,
risk_matrix_default_id: 17
},
{
component_id: 1025,
name: "CHILD SEAT:VEHICLE TETHER ANCHOR",
description: "532000 CHILD SEAT:VEHICLE TETHER ANCHOR",
is_public: true,
is_vehicle: false,
is_equipment: false,
is_tire: false,
is_child_seat: true,
is_active: true,
is_deleted: false,
risk_matrix_default_id: 4
}
]
};
if (incident.components && incident.components.length > 0) {
dataForTemplate.tire_components = incident.components
.filter(e => e.is_tire)
.map(e => {
return `${e.description}`;
})
.join(" ,");
}
console.log(dataForTemplate);
let dataForTemplate = {};
incident = {
complaint_id: 55556473,
components: [
{
component_id: 263,
name: "SEAT BELTS",
description: "150000 SEAT BELTS",
is_public: true,
is_vehicle: true,
is_equipment: false,
is_tire: false,
is_child_seat: false,
is_active: true,
is_deleted: false,
risk_matrix_default_id: 1
},
{
component_id: 300,
name: "TIRES",
description: "190000 TIRES",
is_public: true,
is_vehicle: true,
is_equipment: false,
is_tire: true,
is_child_seat: false,
is_active: true,
is_deleted: false,
risk_matrix_default_id: 17
},
{
component_id: 300,
name: "TIRES",
description: "190000 TIRES example 2",
is_public: true,
is_vehicle: true,
is_equipment: false,
is_tire: true,
is_child_seat: false,
is_active: true,
is_deleted: false,
risk_matrix_default_id: 17
},
{
component_id: 1025,
name: "CHILD SEAT:VEHICLE TETHER ANCHOR",
description: "532000 CHILD SEAT:VEHICLE TETHER ANCHOR",
is_public: true,
is_vehicle: false,
is_equipment: false,
is_tire: false,
is_child_seat: true,
is_active: true,
is_deleted: false,
risk_matrix_default_id: 4
}
]
};
if (incident.components && incident.components.length > 0) {
dataForTemplate.tire_components = incident.components
.filter(e => e.is_tire)
.map(e => {
return `${e.description}`;
})
.join(" ,");
}
console.log(dataForTemplate);
Array.prototype.join already does what you want, so it's just a matter of selecting the right data and calling .join (', '). Here's one technique:
const tireComponentDescriptions = (incident) =>
((incident || {}) .components || [])
.filter (i => i .is_tire)
.map (i => i.description)
.join (', ')
const incident = {complaint_id: 55556473, components: [{component_id: 263, name: "SEAT BELTS", description: "150000 SEAT BELTS", is_public: true, is_vehicle: true, is_equipment: false, is_tire: false, is_child_seat: false, is_active: true, is_deleted: false, risk_matrix_default_id: 1}, {component_id: 300, name: "TIRES", description: "190000 TIRES", is_public: true, is_vehicle: true, is_equipment: false, is_tire: true, is_child_seat: false, is_active: true, is_deleted: false, risk_matrix_default_id: 17}, {component_id: 1025, name: "CHILD SEAT: VEHICLE TETHER ANCHOR", description: "532000 CHILD SEAT: VEHICLE TETHER ANCHOR", is_public: true, is_vehicle: false, is_equipment: false, is_tire: false, is_child_seat: true, is_active: true, is_deleted: false, risk_matrix_default_id: 4}]};
console .log (tireComponentDescriptions (incident))
incident .components [0] .is_tire = true
console .log (tireComponentDescriptions (incident))
incident .components [2] .is_tire = true
console .log (tireComponentDescriptions (incident))
filter through the components, map to the description and join the resulting array afterwards
components.filter(component => component.is_tire).map(component => component.description).join(', ')
Array.map always returns an array of the same length, so will contain undefined values in your example. You could use Array.filter to first filter out any values you don't want before using join
if (incident.components && incident.components.length > 0) {
dataForTemplate.tire_components = incident.components.filter(e => e.is_tire).map(e => e.description).join(' ,');
}
You could also use Array.reduce to filter and map at the same time.
if (incident.components && incident.components.length > 0) {
dataForTemplate.tire_components = incident.components.reduce((output, e) => {
if(e.is_tire) {
output.push(e.description)
}
return output
}, []).join(' ,');
}
You could filter in advance and then map the wanted property.
let dataForTemplate = {},
incident = { complaint_id: 55556473, components: [{ component_id: 263, name: "SEAT BELTS", description: "150000 SEAT BELTS", is_public: true, is_vehicle: true, is_equipment: false, is_tire: false, is_child_seat: false, is_active: true, is_deleted: false, risk_matrix_default_id: 1 }, { component_id: 300, name: "TIRES", description: "190000 TIRES", is_public: true, is_vehicle: true, is_equipment: false, is_tire: true, is_child_seat: false, is_active: true, is_deleted: false, risk_matrix_default_id: 17 }, { component_id: 1025, name: "CHILD SEAT:VEHICLE TETHER ANCHOR", description: "532000 CHILD SEAT:VEHICLE TETHER ANCHOR", is_public: true, is_vehicle: false, is_equipment: false, is_tire: false, is_child_seat: true, is_active: true, is_deleted: false, risk_matrix_default_id: 4 }] };
if (incident.components && incident.components.length > 0) {
dataForTemplate.tire_components = incident.components
.filter(({ is_tire }) => is_tire)
.map(({ description }) => description)
.join(' ,');
}
console.log(dataForTemplate);

Find object in collection with fuzzy matching

I have a collection that looks something like this:
const collection = [
{
name: 'THIS_ITEM',
conditions: {
oneCondition: false,
anotherCondition: false,
yourCondition: false,
myCondition: false
}
}, {
name: 'THAT_ITEM',
conditions: {
oneCondition: false,
anotherCondition: false,
yourCondition: true,
myCondition: false
}
}, {
name: 'THOSE_ITEMS',
conditions: {
oneCondition: true,
anotherCondition: false,
yourCondition: null,
myCondition: false
}
}
];
… and later an object that looks like this:
const condition = {
oneCondition: true,
anotherCondition: false,
yourCondition: true,
myCondition: false
};
I’m trying to match the condition object against the nested conditions objects in collection to find the one that matches so I can retrieve the name property from the matching entry.
The thing that’s throwing me for a loop is the fact that the conditions properties can have “fuzzy” values. By that I mean that if any properties in the source collection are set to true or false they MUST match the values in condition exactly. But if the property in the source collection has a value of null it can match either true or false.
Example:
These would match:
const condition = {
oneCondition: true,
anotherCondition: false,
yourCondition: true,
myCondition: false
};
const collection = [
…
}, {
name: 'THOSE_ITEMS',
conditions: {
oneCondition: true,
anotherCondition: false,
yourCondition: null,
myCondition: false
}
}
];
These would not:
const condition = {
oneCondition: true,
anotherCondition: false,
yourCondition: true,
myCondition: false
};
const collection = [
…
}, {
name: 'THAT_ITEM',
conditions: {
oneCondition: false,
anotherCondition: false,
yourCondition: true,
myCondition: false
}
}, {
…
];
Any suggestions? I’m using Lodash but can’t seem to imagine any solution without an overly-verbose and nested concoction.
You could use Array#filter with Array#every for the conditions and test against null value as wildcard.
var collection = [{ name: 'THIS_ITEM', conditions: { oneCondition: false, anotherCondition: false, yourCondition: false, myCondition: false } }, { name: 'THAT_ITEM', conditions: { oneCondition: false, anotherCondition: false, yourCondition: true, myCondition: false } }, { name: 'THOSE_ITEMS', conditions: { oneCondition: true, anotherCondition: false, yourCondition: null, myCondition: false } }],
condition = { oneCondition: true, anotherCondition: false, yourCondition: true, myCondition: false },
result = collection.filter(o =>
Object.keys(condition).every(k =>
o.conditions[k] === null || o.conditions[k] === condition[k]
)
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use lodash#filter with lodash#isMatch and lodash#omitBy to match the condition against a collection object's condition that doesn't contain any null values.
const result = _.filter(collection, v =>
_.isMatch(condition, _.omitBy(v.conditions, _.isNull))
);
const collection = [
{
name: 'THIS_ITEM',
conditions: {
oneCondition: false,
anotherCondition: false,
yourCondition: false,
myCondition: false
}
}, {
name: 'THAT_ITEM',
conditions: {
oneCondition: false,
anotherCondition: false,
yourCondition: true,
myCondition: false
}
}, {
name: 'THOSE_ITEMS',
conditions: {
oneCondition: true,
anotherCondition: false,
yourCondition: null,
myCondition: false
}
}
];
const condition = {
oneCondition: true,
anotherCondition: false,
yourCondition: true,
myCondition: false
};
const result = _.filter(collection, v =>
_.isMatch(condition, _.omitBy(v.conditions, _.isNull))
);
console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
You can filter the collecting using lodash's _.isMatchWith():
const condition = {"oneCondition":true,"anotherCondition":false,"yourCondition":true,"myCondition":false};
const collection = [{"name":"1","conditions":{"oneCondition":true,"anotherCondition":false,"yourCondition":true,"myCondition":false}},{"name":"2","conditions":{"oneCondition":true,"anotherCondition":false,"yourCondition":false,"myCondition":false}},{"name":"3","conditions":{"oneCondition":true,"anotherCondition":false,"yourCondition":null,"myCondition":false}}];
const result = collection.filter(({ conditions }) =>
_.isMatchWith(condition, conditions, (objValue, othValue) =>
objValue === null || othValue === null || objValue === othValue) // if at least one of the values is null or they are equal
);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
You can use a combination of lodash
.filter(), .every() and .isEqual() methods to loop over the collection and filter only items which have the same conditions as your object:
_.filter(collection, function(c) {
return _.every(_.keys(condition), function(currentKey) {
return c.conditions[currentKey] === null ||
_.isEqual(c.conditions[currentKey], condition[currentKey]);
});
});
Demo:
const collection = [{
name: 'THIS_ITEM',
conditions: {
oneCondition: false,
anotherCondition: false,
yourCondition: false,
myCondition: false
}
}, {
name: 'THAT_ITEM',
conditions: {
oneCondition: false,
anotherCondition: false,
yourCondition: true,
myCondition: false
}
}, {
name: 'THOSE_ITEMS',
conditions: {
oneCondition: true,
anotherCondition: false,
yourCondition: null,
myCondition: false
}
}];
const condition = {
oneCondition: true,
anotherCondition: false,
yourCondition: true,
myCondition: false
};
var result = _.filter(collection, function(c) {
return _.every(_.keys(condition), function(currentKey) {
return c.conditions[currentKey] === null ||
_.isEqual(c.conditions[currentKey], condition[currentKey]);
});
});
console.log(result);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
<script src="http://underscorejs.org/underscore-min.js"></script>

node - Converting to JSON fails, but can print in console

I'm attempting to convert an array to JSON to be sent to a client. Here is what the data looks like in console:
[ NL: [ true, true, true, true, true, true, true, true, true, true, true, true ],
LU: [ true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
false,
false,
false ],
SE: [ false, false, false ] ]
However when I run this (res being an express.js socket):
console.log(st.bot.serverStatus);
res.send(JSON.stringify(st.bot.serverStatus));
I get the output in console like expected, but I get [] from the web browser. What am I doing wrong?
PS: I am unable to change the format of the elements, they are generated by this method:
if(st.bot.serverStatus[tmp.country] !== undefined) {
st.bot.serverStatus[tmp.country][st.bot.serverStatus[tmp.country].length] = alive;
} else {
st.bot.serverStatus[tmp.country] = [ alive ];
}
It's not valid syntax at SE: and LE: since it is an array and not an object. Change the outermost [] to {} or change : to ,
Use either:
console.log(JSON.stringify({ NL: [ true, true, true, true, true, true, true, true, true, true, true, true ],
LU: [ true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
false,
false,
false ],
SE: [ false, false, false ] } ));
Or:
console.log(JSON.stringify([{ NL: [ true, true, true, true, true, true, true, true, true, true, true, true ]},
{LU: [ true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
false,
false,
false ]},
{SE: [ false, false, false ] }] ));
Your JSON format is incorrect.
Use something like
jsonformatter.curiousconcept.com
or
jsoneditoronline.org
To validate your JSONs

Categories

Resources