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];
/*....*/
Related
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;
}
I'm working with jQuery Sortable to create some block of codes with nested list ( for loop and function block), then I got this json string use JSON.stringify on console.log(jsonString):
{
"codes": [
[
{
"id": "code_run",
"code": "run",
"name": "code_when_run"
},
{
"id": "",
"code": "loop",
"name": "code_block_repeat",
"children": [
[
{
"id": "",
"code": "up",
"name": "code_arrow_up"
},
{
"id": "",
"code": "up",
"name": "code_arrow_up"
}
]
]
}
]
]
}
Here's my code from the jQuery sortable's example :
let oldContainer, codeBlockId, codeBlockItem;
$("ol.nest_workspace").sortable({
group: 'nested',
onDragStart: function ($item, container, _super) {
// Duplicate items of the no drop area
if(!container.options.drop)
$item.clone().insertAfter($item);
_super($item, container);
},
afterMove: function (placeholder, container) {
if(oldContainer != container){
if(oldContainer)
oldContainer.el.removeClass("active");
container.el.addClass("active");
oldContainer = container;
}
},
onDrop: function ($item, container, _super) {
container.el.removeClass("active");
$item.addClass("block_code_on_workspace");
var data = group.sortable("serialize").get();
var jsonString = JSON.stringify({"codes":data}, null, '\t');
console.log(jsonString);
_super($item, container);
},
});
How can I process the sub array (children[]) ?
I have plan to make it all block as a real codes, so it could execute with another function.
I may expect the text output printed some function like moveUp(), or if its loop with some function inside, then would be like :
for (var i = 0; i < 3; i++) {
moveUp();
}
Any help or suggest would be great, thanks!
If your JSON string will always look like this. Then you can target there “children" array like this.
I wrote this code base only on the format of the JSON that you have above.
const childrenArr = jsonString.codes[0][1].children;
Based on the code we’re you are stringifying your data this code should work.
var jsonString = JSON.stringify({"codes":data}, null, '\t');
console.log(jsonString),
ChildrenArr = jsonString.codes[0][1].children;
I've found a solution for my problem, here's the code :
$("ol.nest_workspace").sortable({
group: 'nested',
onDragStart: function ($item, container, _super) {
// Duplicate items of the no drop area
if(!container.options.drop)
$item.clone().insertAfter($item);
if($item.hasClass('RepeatCode')){
$item.attr('id','block_loop_function_drag');
}
_super($item, container);
},
afterMove: function (placeholder, container) {
if(oldContainer != container){
if(oldContainer)
oldContainer.el.removeClass("active");
container.el.addClass("active");
oldContainer = container;
}
},
onDrop: function ($item, container, _super) {
$(".coding-script").empty();
container.el.removeClass("active");
$item.addClass("block_code_on_workspace");
$hasID = document.getElementById('block_loop_function_drag');
var data = group.sortable("serialize").get();
// console.log(data);
for(var i = 0; i < data[0].length; i++){
if($hasID){
$item.attr('id','block_loop_function_'+i+'');
}
var obj = data[0][i];
if(obj.hasOwnProperty("children")){
var objChildren = obj.children[0];
console.log(obj.code +'-'+i);
ConvertToCodeScripts(obj.code, i);
for(var j = 0; j < objChildren.length; j++){
console.log('loop-'+i+'-'+objChildren[j].code);
ConvertToCodeScripts('loop-'+i+'-'+objChildren[j].code, i);
}
}
else{
console.log(obj.code);
ConvertToCodeScripts(obj.code, i);
}
console.log('lha - '+i);
}
_super($item, container);
},
});
But let me know if you guys have a better solution.
Cheers
I currently have a complex orders array (coming from a JSON client) that contains multiple orders like this (contains 2):
0: {
"employee": "Nicole"
"total": 13
"lineItems": {
"elements": [2]
0: {
"name": "Burger"
"price": 8
}
1: {
"name": "Lamb"
"price": 6.50
}
}
}
1: {
"employee": "Dan"
"total": 11
"lineItems": {
"elements": [2]
0: {
"name": "Lamb"
"price": 4.50
}
1: {
"name": "Meatballs"
"price": 6.50
}
}
}
What I want to do is create a new array that loops through the above and creates new items array based on the name of the lineItems object above. i.e. final output looks something like this:
var items = {
"Burger" = {
"totalSpent" : 8
},
"Lamb" = {
"totalSpent" : 13
// Note this totalSpent is an iteration or sum of all "price" items where name/id = "Lamb"
},
"Meatballs" = {
"totalSpent" : 4.50
}
}
I'm more used to PHP and have tried a number of different versions of this but can't seem to get the desired output. Here's what I've got so far:
var orders = //As above//
// Initialising new array to hold my final values
var orderItems = [];
for (var i = 0, len = orders.length; i < len; i++){
for(var e = 0, leng = orders[i]['lineItems']['elements'].length; e < leng; e++){
var totalSpent = 0;
var id = orders[i]['lineItems']['elements'][e]['name'];
if (orders[id] in orderItems[id]){
// overwrite existing array item
orderItems[id]['totalSpent'] += orders[i]['lineItems']['elements'][e]['price'];
orderItems[id].push({totalSpent : orderItems[id]['totalSpent']});
}
else {
// Create new array item
orderItems.push(id);
orderItems[id].push({totalSpent : orders[i]['lineItems']['elements'][e]['price']});
}
}
}
Edit:
Had to correct your orders syntax, I added it to my answer so you can run the Javascript Snippet;
Changed the whole dot notation to bracket notation to make it easier to read and understand;
Corrected the bug about items remaining an empty array (it was in the inner for);
var orders = [
{
"employee": "Nicole",
"total": 13,
"lineItems": {
"elements": [
{
"name": "Burger",
"price": 8
},
{
"name": "Lamb",
"price": 6.50
}
]
}
},
{
"employee": "Dan",
"total": 11,
"lineItems": {
"elements": [
{
"name": "Lamb",
"price": 4.50
},
{
"name": "Meatballs",
"price": 6.50
}
]
}
}
];
var items = {};
// loop in orders array
for (var i = 0; i < orders.length; i++) {
var elements = orders[i]["lineItems"]["elements"];
// loop in orders[i]["lineItems"]["elements"] object
for (var eIndex in orders[i]["lineItems"]["elements"]) {
// Add new item if it doesn't already exist
if (!items.hasOwnProperty(elements[eIndex]["name"])) {
items[elements[eIndex]["name"]] = {"totalSpent": elements[eIndex]["price"]};
} else {
// If it exists, sum totalSpent
items[elements[eIndex]["name"]]["totalSpent"] += elements[eIndex]["price"];
}
}
}
console.log(items);
PS: To find out why I'm using bracket notation instead of dot notation, check this question, it's good to know!
First of all, there are some error in your order array, note the difference between {} (for objects) and []. Then it is just simple use of the map function to iterate over the arrays.
See your browser console (F12) for the result of this snippet
var orders = [{
"employee": "Nicole",
"total": 13,
"lineItems": {
"elements": [{
"name": "Burger",
"price": 8
}, {
"name": "Lamb",
"price": 6.50
}
]
}
}, {
"employee": "Dan",
"total": 11,
"lineItems": {
"elements": [{
"name": "Lamb",
"price": 6.50
}, {
"name": "Meatballs",
"price": 4.50
}]
}
}]
var items = {}
orders.map(function(order) {
order.lineItems.elements.map(function(elem) {
if (items[elem.name]) {
items[elem.name].totalSpent += elem.price
} else {
items[elem.name] = {"totalSpent": elem.price}
}
})
})
console.log(items)
I would like to parse and display arbitrary-level JSON snippets as HTML. By arbitrary-level I mean there is no pre-definied structure. For example:
"CustomFields": [
{
"Main": [
{
"None": [
{
"SDOM Date": "2014-12-24"
},
{
"User Defined 31": "2009-03-02"
}
]
},
{
"Contract Data": [
{
"Status2": "Active"
},
{
"User Defined 112": "N"
}
]
}
]
}
Besides the CustomFields root element, everything under it is unpreditable. But basically there are layers of objects which are each an array of other objects, until you finally arrive at an object value. In the example above there are 4 levels. But there can be any number of them.
What I'd like is to display something like:
Main
None
SDOM Date: 2014-12-24
User Defined 31: 2009-03-02
Contract Data
Status2: Active
User Defined 112: N
Try this..
var json = {"CustomFields": [
{
"Main": [
{
"None": [
{
"SDOM Date": "2014-12-24"
},
{
"User Defined 31": "2009-03-02"
}
]
},
{
"Contract Data": [
{
"Status2": "Active"
},
{
"User Defined 112": "N"
}
]
}
]
}]};
function jsonToHtml(array){
var html = '<ul>';
for (var i=0; i<array.length; i++){
if (typeof array[i] == 'object'){
for (var j in array[i]){
var innerHTML = (typeof array[i][j]=='object')?jsonToHtml(array[i][j]):' : '+array[i][j];
html += '<li>'+j+innerHTML+'</li>';
}
}
}
html += '</ul>';
return html;
}
aaa.innerHTML = jsonToHtml(json.CustomFields);
<div id="aaa"></div>
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+.