Accurate value from the JSON Array - javascript

Trying to match the value with the JSON value by wrirting a for loop, but everytime once the loop is completes it is returning 2345 value only. Where am I going wrong can anyone help me out.
And I have a term which dynamically generates a string value.
var mKey = doc.search.searchBy.split(",")[0].split("=")[1].replace(/\s+/, "").toLowerCase();
JSON:
{
"records" : {
"cat1" : [
{
"id" : 1234,
"label":"a"
},
{
"id" : 2345,
"label":"b"
}
],
"cat2" : {
"id" : 12345,
"label" : "c"
}
}
}
JS:
var array = doc.records.cat1;
for (var i=0; i<array.length; i++) {
var oID = array[i].id.toString();
}
if (oID === "2345" && mKey=="Apple") {
console.log("Apple");
break;
}
else if (oID === "1234" && mKey=="Banana") {
console.log("Banana")
}
else {
console.log('other fruits');
}

You need to place your if statement within the for loop so that it relates to the current iteration:
var array = doc.records.cat1;
for (var i = 0; i < array.length; i++) {
var oID = array[i].id.toString();
if (oID === "2345") {
console.log("success");
}
else if (oID === "1234") {
console.log("error")
}
else {
console.log('other');
}
}
Example fiddle
Note that a break statement is irrelevant inside an if block.

You have closed your loop in wrong place, I guess
for (var i=0; i<array.length; i++) {
var oID = array[i].id.toString();
if (oID === "2345") {
console.log("success");
break;
}
else if (oID === "1234") {
console.log("error")
}
else {
console.log('other');
}
}

All if structure comes under for loop
var array = doc.records.cat1;
for (var i=0; i<array.length; i++) {
var oID = array[i].id.toString();
if (oID === "2345" && mKey=="Apple") {
console.log("Apple");
break;
}
else if (oID === "1234" && mKey=="Banana") {
console.log("Banana")
}
else {
console.log('other fruits');
}
}

Related

Iterate over a Javascript Object and perfom conditional on values

So i have a JS Object like that :
let object =
{
"key1":"value1",
"key2":"value2",
"key3":"value3"
}
For iterating, i use this : for (let i = 0; i < Object.keys(object).length; i++)
Now, what i want to do is basically this :
let value;
if (data === undefined || data === "") {
value = []
} else if (data.includes(",")) {
value = data.split(",")
} else if (data.includes(".")) {
value = data.split(".")
} else {
value = data.split(" ");
}
So, i tried Object.values(entries_array).split(",") but split is not an Object method. So if you can help me to find a solution.
Thanks in advance.
Edit: Sorry, i'll try to describe more what i want to achieve. I want with the code, to obtain my object variable changed with the same keys but with the values splitted.
For example if the value has a comma, i want to split the value. If not, do nothing.
For now, i have this :
let object =
{
"key1":"value1",
"key2":"value2",
"key3":"value3"
}
const entries = Object.entries(object);
const entries_array = Object.fromEntries(entries)
let data_val;
for (let i = 0; i < Object.keys(entries_array).length; i++) {
Object.values(entries_array).forEach(val => {
if (val === undefined || val === "") {
data_val = []
} else if (val.includes(",")) {
data_val = val.split(",")
} else if (val.includes(".")) {
data_val = val.split(".")
} else {
data_val = val.split(" ");
}
});
}
return entries_array;
function reassignValueAsArray(obj, [key, value]) {
obj[key] = value.split(/\s*[., ]\s*/);
return obj;
}
function reassignKeyValuesAsArray(obj) {
return Object
.entries(obj)
.reduce(reassignValueAsArray, obj);
}
const sampleObject = {
"key1": "value1,value1b",
"key2": "value2.value2b",
"key3": "value3 value3b",
"key4": "value4.value4b,value4c value4d",
"key5": "value5-value5b-value5c-value5d",
};
reassignKeyValuesAsArray(sampleObject);
console.log(sampleObject);
.as-console-wrapper { min-height: 100%!important; top: 0; }

Serialization of JS object with different logic for object's properties

Hi I need to convert the the numeric values of my object to string. But different properties has different transformation rules.
My sample object:
{
name: "Name"
sRatio: 1.45040404
otherMetric: 0.009993
}
I use JSON.stringify to convert my initial object.
let replacemet = {}
JSON.stringify(metrics[0], function (key, value) {
//Iterate over keys
for (let k in value) {
if ((k !== "sRatio") || (k !== "name")) {
replacemet[k] = (100*value[k]).toFixed(2) + "%"
} else {
if( k === "name") {
replacemet[k] = "yo!"+value[k]
} else{
replacemet[k] = value[k].toFixed(2)
}
}
}
})
But my conditions are not triggered and all properties are converting on the same manner.
The job of the replacer callback is not to fill in some global replacemet object but rather to return a new value.
I think you are looking for something along the lines of
JSON.stringify(sample, function (key, value) {
if (key == "sRatio") {
return value.toFixed(2);
} else if (key == "name") {
return "yo!"+value;
} else if (typeof value == "number") {
return (100*value).toFixed(2) + "%"
} else {
return value;
}
})
Try using switch block that will be really good for this. Detailed description on switch.
let replacemet = {}
JSON.stringify(metrics[0], function (key, value) {
//Iterate over keys
for (let k in value) {
switch(k) {
case "name":
replacemet[k] = "yo!"+value[k];
break;
case "sRatio":
replacemet[k] = value[k].toFixed(2);
break;
default:
replacemet[k] = value[k].toFixed(2);
}
}
})
Hope to help you . I add when dynamic property
metrics =
[
{
name: "Name",
sRatio: 1.45040404,
otherMetric:0.009993
},
{
name: "Name1",
sRatio: 2.45040404,
otherMetric: 1.009993
}
]
;
let source = JSON.stringify(metrics);
let arrJson = new Array();
//arrJson = {};
metrics.forEach(function(value){
let replacemet = {};
for(var k in value) {
if( k.toString().trim() == "name") {
replacemet[k] = "yo!"+value[k] ;
}
else
if ( ( k.toString().trim() !== "sRatio") && ( k.toString().trim() !== "name")) {
replacemet[k] = (100* value[k] ).toFixed(2).toString() + "%" ;
} else {
replacemet[k] = value[k].toFixed(2) ;
}
}
arrJson.push(JSON.stringify(replacemet)) ;
});
console.log(arrJson);

handle multiple conditions on a string

I've created a function which takes a string and replace it's ending substring, so if the string ends with AddFiche, EditFiche or Fiche they should be replaced with Liste, and some other conditions this is what I tried:
function _getParentComponent(component){
if(component.endsWith('AddFiche')){
return component.replace('AddFiche', 'Liste');
}else if(component.endsWith('EditFiche')){
return component.replace('EditFiche', 'Liste');
}else if(component.endsWith('Fiche')){
return component.replace('Fiche', 'Liste');
}else if(component === "selection"){
if($rootRouter._outlet.previousInstruction.componentType === "import"){
return "import";
}
}else if(component === "result"){
if($rootRouter._outlet.previousInstruction.componentType === "selection"){
return "import";
}
}else if(component.startsWith("request")){
if($rootRouter._outlet.previousInstruction.componentType === "dynamicRouting"){
return "dynamicRouting";
}
}else{
return component;
}
}
As you can see there are a lot of if elses, isn't there any other way to do this ? since I might add other conditions later, and the code looks ugly with all those if elses.
var replaces = [{
match: 'AddFiche',
replace: 'Liste'
},
{
match: 'EditFiche',
replace: 'Liste'
},
{
match: 'Fiche',
replace: 'Liste'
}
]
function _getParentComponent(component) {
var done = false;
for (var r of replaces) {
if (component.endsWith(r.match)) {
return component.replace(r.match, r.replace);
}
}
if (component === "selection") {
if ($rootRouter._outlet.previousInstruction.componentType === "import") {
return "import";
}
} else if (component === "result") {
if ($rootRouter._outlet.previousInstruction.componentType === "selection") {
return "import";
}
} else if (component.startsWith("request")) {
if ($rootRouter._outlet.previousInstruction.componentType === "dynamicRouting") {
return "dynamicRouting";
}
} else {
return component;
}
}
console.log("Input: LoremIpsumFiche");
console.log("Output:",_getParentComponent("LoremIpsumFiche"));
Can be this
var ends = ['One', 'Two', 'Wood'];
var words = ['LOne', 'ROnes', 'Two2', 'TwoTwo', 'No Wood', 'Woodless'];
var replaced = "REPLACED";
for(var i = 0; i < words.length; i++) {
for(var j = 0; j < ends.length; j++) {
if(words[i].endsWith(ends[j])) {
words[i] = words[i].replace(new RegExp(ends[j] + '$'), replaced);
break;
}
}
}
console.log(words);

Unable to display array content

var dataHolder = [
{
"letterA" : "Fruits",
"letterB" : "Veges",
"letterC" : "Meat"
}
];
console.log(dataHolder[0].letterA);
var result = "";
function getData(myLetter) {
for (var i = 0; i < dataHolder.length; i++) {
if(dataHolder[i][myLetter] === myLetter){
console.log(dataHolder[i][myLetter]);
}
else{
console.log("No data found");
}
}
}
getData("letterA");
This is my code and i'm just trying to match the content of the array with the passed parameter, but every time it's giving No data found as output and not the matching content, it seems i'm missing something very basic here.
Any help would be highly appreciated.Thanks!!
You matching was wrong.
you are matching the letters == fruites .You should check is the key exist or not ,that's enough using hasOwnProperty()
Check this below. i was mention the error
var dataHolder = [{
"letterA": "Fruits",
"letterB": "Veges",
"letterC": "Meat"
}];
var result = "";
function getData(myLetter) {
for (var i = 0; i < dataHolder.length; i++) {
console.log('this is the pblm '+dataHolder[i][myLetter] +' != '+myLetter)
if (dataHolder[i].hasOwnProperty(myLetter)) {
console.log(dataHolder[i][myLetter]);
} else {
console.log("No data found");
}
}
}
getData("letterA");
For your way use with for...in
var dataHolder = [{
"letterA": "Fruits",
"letterB": "Veges",
"letterC": "Meat"
}];
var result = "";
function getData(myLetter) {
for (var i in dataHolder) {
if (dataHolder[i].hasOwnProperty(myLetter)) {
console.log(dataHolder[i][myLetter]);
} else {
console.log("No data found");
}
}
}
getData("letterA")
You are comparing value with key that is wrong.
The hasOwnProperty() method returns a boolean indicating whether the
object has the specified property as own (not inherited) property.
Use hasOwnProperty to check key exists or not.
dataHolder[i].hasOwnProperty(myLetter)
var dataHolder = [
{
"letterA" : "Fruits",
"letterB" : "Veges",
"letterC" : "Meat"
}
];
var result = "";
function getData(myLetter) {
for (var i = 0; i < dataHolder.length; i++) {
if(dataHolder[i].hasOwnProperty(myLetter)){
console.log(dataHolder[i][myLetter]);
}
else{
console.log("No data found");
}
}
}
getData("letterA");

Iterate over an object with delay

I am trying to iterate over nested children of an object, but need have a delay after every child. Normally I would just write a recursive function and use that to iterate over an object, but this happens near instantly. How can I do this with a delay?
I thought about saving the index in a variable and accessing children using that, then increasing the index every time a setInterval is run, but how can this be expanded to take nesting into account?
Function to iterate:
function iter(obj) {
for (var i = 0; i < obj.length; i++) {
console.log(obj[i].command);
if (typeof obj[i].contains == "object") {
iter(obj[i].contains);
}
}
}
iter(object);
Example object:
[
{
"command":"do (5)",
"contains":[
{
"command":"move.up()",
"contains":false
},
{
"command":"move.left()",
"contains":false
},
{
"command":"if (kind == \"item\")",
"contains":[
{
"command":"move.down()",
"contains":false
}
]
},
{
"command":"move.right()",
"contains":false
}
]
}
]
First create a flat array from the hierarchy:
function iter(obj) {
var result = [];
for (var i = 0; i < obj.length; i++) {
result.push(obj[i]);
if (typeof obj[i].contains == "object") {
result = result.concat(iter(obj[i].contains));
}
}
return result;
}
var items = iter(object);
Now you can iterate the array with a timer and an index:
var index = 0;
var timer = window.setInterval(function(){
if (index < items.length) {
console.log(items[index].command);
index++;
} else {
window.clearInterval(timer);
}
}, 1000);
Demo:
var object = [
{
"command":"do (5)",
"contains":[
{
"command":"move.up()",
"contains":false
},
{
"command":"move.left()",
"contains":false
},
{
"command":"if (kind == \"item\")",
"contains":[
{
"command":"move.down()",
"contains":false
}
]
},
{
"command":"move.right()",
"contains":false
}
]
}
];
function iter(obj) {
var result = [];
for (var i = 0; i < obj.length; i++) {
result.push(obj[i]);
if (typeof obj[i].contains == "object") {
result = result.concat(iter(obj[i].contains));
}
}
return result;
}
var items = iter(object);
var index = 0;
var timer = window.setInterval(function(){
if (index < items.length) {
log(items[index].command);
index++;
} else {
window.clearInterval(timer);
}
}, 1000);
function log(str) {
document.getElementById('log').innerHTML += str + '<br>';
}
<div id="log"></div>

Categories