right way to add an object into array with looping through - javascript

i know it is a repeated Question but i can't figure the proper way to add an object to an array with checking if there is match or not like , this is a function that loops through an array of words and check if the entered word is in the array so increase its count by 1 , if not push this word to the array
and set its count by 0
function addWord(request, response) {
var data = request.params;
var word = data.word;
var reply;
for (i = 0; i < Words.length; i++){
if (Words[i].type != word){
reply = {
msg: "not Found but added"
};
Words.push({"type": word , "count": 0});
} else if (Words[i].type == word) {
reply = {
msg: "already Found and added"
};
Words.count++;
}
}
var x = JSON.stringify(Words, null, 2);
fs.writeFile('count.json', x, finished);
function finished(){
console.log('Yay')
}
the problem is the output gives me four new elements not just one and with Count 1 not 0, lets say that i added the word Music the output is like so
[
{
"type": "physical",
"count": 8
},
{
"type": "WCAP",
"count": 2
},
{
"type": "BLQ",
"count": 2
},
{
"type": "unable",
"count": 2
},
{
"type": "music",
"count": 1
},
{
"type": "music",
"count": 1
},
{
"type": "music",
"count": 1
},
{
"type": "music",
"count": 1
},
]

The problem is that you first must loop over all the words before deciding if a word is in the list or not. You could fix your code to look like this:
var found = false
for (i = 0; i < Words.length; i++){
if (Words[i].type == word){
Words[i].count++
reply = {
msg: "already Found and added"
};
found = true;
break;
}
}
if (!found) {
Words.push({"type": word , "count": 0});
reply = {
msg: "already Found and added"
};
}
And just in case, here is a snippet with a simpler addWord function that might help you:
var Words = [];
function addWord(word) {
for (var i=0; i < Words.length; i++) {
if (word == Words[i].type) {
Words[i].count++
return
}
}
Words.push({type: word, count: 0})
}
addWord('stack')
addWord('overflow')
addWord('stack')
console.log(Words)

try the following function:
function findWord(Words) {
let found = Words.some(word => word.type == yourWord)
return found;
}

Related

Filtering result using Javascript

I am trying to filter an array, but am having issues with returning only the values which are true (status: yes).
var arr = {
"status": "Yes"
},
{
"status": "No"
},
{
"status": "No"
},
{
"status": "No"
}
var filteredResult = [];
for (var i = 0; i < arr.length; i++) {
if(arr[i].status == "Yes") {
filteredResult.push(status);
}
}
console.log (filteredResult);
I am still learning JS, but I hope to improve.
Thank you.
I don't think this code compiles - you need to include square brackets to declare an array.
const arr =
[{ "status": "Yes" },
{ "status": "No" },
{ "status": "No" },
{ "status": "No" }]
Then to filter it, just do
const results = arr.filter((item) => { return item.status === "Yes" })
Your syntax is wrong so for loop won't work. The array should be inside "[]". Refer to the below code. I have tested and is working fine.
If you want to get list of all object having status "Yes", then use filteredResult.push(arr[i]), else filteredResult.push(arr[i].status) if you need strings of "Yes"
var arr = [{
"status": "Yes"
},
{
"status": "No"
},
{
"status": "No"
},
{
"status": "No"
}]
var filteredResult = [];
for (var i = 0; i < arr.length; i++) {
if(arr[i].status == "Yes") {
filteredResult.push(arr[i]);
}
}

Looping between functions and storing results

I would like produce a list of grouped JSON elements according to a specific criteria, but I am unable to make my loop work.
The function should make groups of with 12 bottles and return a single JSON list. So in this example, the function should extract the 3 first items and then run again to extract the remaining ones. But I am looping forever... Thank you in advance,
var data = {
"order": [
{ "product": "MAXIMUS", "quantity": "3" },
{ "product": "COLECCION", "quantity": "3" },
{ "product": "CABERNET FRANC", "quantity": "6" },
{ "product": "CHARDONNAY", "quantity": "6" },
{ "product": "SAUVIGNON BLANC", "quantity": "6" }
]
};
var qtd = data.order;
var size = qtd.length;
var addline = '';
var add = '';
var total = 0;
var i = 0;
var a = 0;
var c = '';
function MakeList(i, add) {
for (i < 0; total < 12; i++) {
total += parseInt(qtd[i].quantity);
addline = addline + '{' + '"quantity": "' + qtd[i].quantity + ' units"},';
i = i++;
add = '{"Box of 12":[' + addline.slice(0, -1) + "]}";
}
return [i, add];
}
function BuildLabels(i, add) {
for (i < 0; c = "true"; i++) {
c = a[0] < size;
a += MakeList(i, add);
i = i++;
}
return a;
}
var results = BuildLabels(i, add);
output = { id: 3, results };
for (i < 0; c = "true"; i++)
something weird is happening here. You don't set any condition on cycle to stop, you just assign value "true" to c. Try to use == instead of =; also initialization looks strange - set i to 0. Apparently, It will make the whole thing work (at least the loop will stop at some point), but in the end I get that the variable results is equal to 0. There are other mistakes/weird stuff out there. Propably, you wanted to achieve something like this:
var data = {
"order": [
{ "product": "MAXIMUS", "quantity": "3" },
{ "product": "COLECCION", "quantity": "3" },
{ "product": "CABERNET FRANC", "quantity": "6" },
{ "product": "CHARDONNAY", "quantity": "6" },
{ "product": "SAUVIGNON BLANC", "quantity": "6" }
]
};
function MakeList(data) {
var selected = [], bottlesNum = 0;
for (var i = 0; bottlesNum < 12; i++) {
selected.push(data.order[i]);
bottlesNum += parseInt(data.order[i].quantity);
}
return selected;
}
var results = MakeList(data);
// now it is a JS object:
console.log({ id: 3, results: results });
// if you want it to be a JSON string, use JSON.stringify():
console.log(JSON.stringify({ id: 3, results: results }));
check it out.
UPDATE
var data = {
"order": [
{ "product": "MAXIMUS", "quantity": "3" },
{ "product": "COLECCION", "quantity": "3" },
{ "product": "CABERNET FRANC", "quantity": "6" },
{ "product": "CHARDONNAY", "quantity": "6" },
{ "product": "SAUVIGNON BLANC", "quantity": "6" }
]
};
function makeGroup(data, max) {
var selected = [], bottlesNum = 0;
while(data.order.length) {
if(bottlesNum + +data.order[0].quantity > max) break;
var order = data.order.shift();
bottlesNum += +order.quantity; // casting to Number
selected.push(order);
}
return selected;
}
function splitOrder(data, max) {
while(data.order.length) {
var results = makeGroup(data, max);
if(!results.length) {
console.log("Error: a product's quantity is greater than max. size of the group. Try to increase max. size of the group.");
break;
}
console.log({ results: results });
}
}
// 2nd argument - max. size of the group. In case of 12 there will be 2 groups - of 3, 3, 6 and 6, 6 bottles
splitOrder(data, 12);
// Also notice that if max. size of the group is a changing value and can be set somehow to, lets say, 4 which is fewer than number of some products (6) in our order. So, it is impossible to complete such a task without taking some additional steps to handle this situation. For example, we could filter our data beforehand to exclude products with numbars greater than 4 and then form groups based on the rest of the data. Or we can treat products with number equal to 6 as if they satisfy our constraint etc.

javascript multi dimensional array

I am trying to create a multidimentional arrya in javascript where I can add items in the following fashion:
var foo = {
"Internal": {
"0":
{
"pic_id":"15011",
"description":"Picture of a cpu",
"localion":"img.cloudimages.us/2012/06/02/mycpu.png",
"type":"png"
},
"1":{
"pic_id":"15011",
"description":"Picture of a cpu",
"localion":"img.cloudimages.us/2012/06/02/mycpu.png",
"type":"png"
}
},
"External":
{
"0":
{
"pic_id":"15014",
"description":"Picture of a cpu",
"localion":"img.cloudimages.us/2012/06/02/mycpu.png",
"type":"png"
}
}
};
but I don't know how to get my value into the main category. I got the following code
vm.classificationNames = [,];
for (var i = 0; i < vm.classificationNames.length; i++) {
vm.allGroupsInClassifications.push(vm.classificationNames[i]);
}
for (var i = 0; i < data.length; i++) {
var item = data[i];
if (item.classification != null) {
} else if (item.classification == null) {
vm.classificationNames['Internal'][item];
}
}
console.log(vm.classificationNames);
I also tried to use the following without any luck:
vm.classificationNames['Internal'].push(item);
Does anyone know what I'd be doing wrong? thanks for the help in advance.
Thats because its an object, not an array.
Change your inner object to an array and push will work
var foo = {
"Internal": [ // <--- Note the square braces
{
"pic_id": "15011",
"description": "Picture of a cpu",
"localion": "img.cloudimages.us/2012/06/02/mycpu.png",
"type": "png"
},
{
"pic_id": "15011",
"description": "Picture of a cpu",
"localion": "img.cloudimages.us/2012/06/02/mycpu.png",
"type": "png"
}
], // <--- Note the square braces
"External": [ // <--- Note the square braces
{
"pic_id": "15014",
"description": "Picture of a cpu",
"localion": "img.cloudimages.us/2012/06/02/mycpu.png",
"type": "png"
}
] // <--- Note the square braces
};
foo['Internal'].push(item);
Try iterating over the dictionary with
for(var key in vm.classificationNames) {
var entry = vm.classificationNames[entry];
/*....*/

change the value of object using loop [duplicate]

This question already has answers here:
JavaScript Object Mirroring/One-way Property Syncing
(2 answers)
Closed 7 years ago.
I have an object as,
var obj = [
{
"name": "a",
"value": "1"
},
{
"name": "b",
"value": "2"
},
{
"name": "c",
"value": "3"
}
]
I have a large object with more than 50 values.
how can I change the value key using its name
and what is the best looping technique for this.
I tried for loop for this like,
for(i = 0; i < obj.length; i++) {
if(obj[i].name == "b") {
// some other functionality
obj[i].value = "some_value";
}
}
But, it takes long time and sometimes for loop goes for next turn before if condition is executed.
Please explain how to solve it or is there any other looping technique
you can use forEach , but as far your hitting the performance its not best ,
you can use map but native for loop is fastest compared to map too
https://jsperf.com/native-map-versus-array-looping
Map , which runs on the each item of the array and return the new array
obj.map(function(item){
if(item.name === "b"){
item.value = "some_value"
}
return item;
})
You can try this :
$(document).ready(function(){
var obj = [
{
"name": "a",
"value": "1"
},
{
"name": "b",
"value": "2"
},
{
"name": "c",
"value": "3"
}
]
for(i = 0; i < obj.length; i++) {
(function(i){
if(obj[i].name === "b") {
console.log(obj[i].name);
// some other functionality
obj[i].value = "some_value";
}
})(i);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I think what you had was quite ok. As one of the comments stated, there was a mistake in the IF-statement which prevented it from being triggered.
I am not sure theres a faster way to proces the JSON object than the way you did. Here's a JSFiddle with some small changes.
function ReplaceValue(name, val) {
for (i = 0; i < obj.length; i++) {
if (obj[i].name == name) {
// some other functionality
obj[i].value = val;
break;
}
}
alert(JSON.stringify(obj, null, 2));
}
Map is your friend!
var obj = [
{ "name": "a", "value": "1" },
{ "name": "b", "value": "2" },
{ "name": "c", "value": "3" }
];
var newObj = obj.map((elm) => {
if(elm.name === "b") elm.value = "some value";
return elm;
});
Is this something like what you were looking for?
In lodash you can do something like this:
`
var obj = [
{
"name": "a",
"value": "1"
},
{
"name": "b",
"value": "2"
},
{
"name": "c",
"value": "3"
}
];
_.transform(arr, function(r, n){
if(n.name == 'b'){
r.push({name: n.name, value: 'some value'})}
else{
r.push(n)
}
})
`

JSON Data Fuzzy merge

I have a JSON data like this
{
"array": {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"PARENT": [
{
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}
]
},
"InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
}
]
}
}
}
I need to search for fuzzy data and merge. For example InvestmentsDeposits and InvestmentsDeposits$$$d need to be merged because it matches closely in name
Need to use javascript for this
For now I can make sure source data will always have $$$d at the end to merge with the target data without $$$d i.e., InvestmentDeposits.
My final merged content should be like this
{
"array": {
"InvestmentsDeposits": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
"text": "newtext"
}
]
}
}
}
any help on this one?
What I have tried so far
var json0 = {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"PARENT": [
{
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}
]
}
};
var json1 =
{
"InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
}
]
}
};
// Merge object2 into object1, recursively
$.extend( true, json0, json1 );
I am able to merge the data if i am able to split the InvestmentDeposits and InvestmentDeposits$$$d in to two distinct JSON objects but how to split and move the $$$d data in to another object? to make the jquery extend work
Use Object.keys() to find an object's keys and figure out what data to move over. You can compare the first key with the others to find matches, then remove the keys you just looked at until all of them are gone. Here's an example with a similar object.
var dat = {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}, "InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
},
"NotLikeTheOthers": {
"Um": "Yeah."
}
};
var result = {}; // This will be the merged object
var keys = Object.keys(dat); // Contains keys
while(keys.length) {
var i=1;
for(; i<keys.length; i++) { // Find matches
if(keys[0] == keys[i] + '$$$d') { // Match type 1
result[keys[i]] = dat[keys[i]]; // Copy orig
for(var j in dat[keys[0]]) { // Replace values
result[keys[i]][j] = dat[keys[0]][j];
}
keys.splice(i,1);
keys.shift();
i = 0;
break;
} else if(keys[i] == keys[0] + '$$$d') { // Reverse matched
result[keys[0]] = dat[keys[0]];
for(var j in dat[keys[i]]) {
result[keys[0]][j] = dat[keys[i]][j];
}
keys.splice(i,1);
keys.shift();
i = 0;
break;
}
}
if(i > 0) { // Didn't find a match
result[keys[0]] = dat[keys[0]];
keys.shift();
}
}
alert(JSON.stringify(result));
Note that Object.keys() requires IE9+.

Categories

Resources