Can anybody help me I am new to javascript. I am not able to understand the below line of code. I spend hours to debug this code but I am not able to rectify.
var data = [
{"name":"123123123123"},
{"name":"123123123124"},
{"name":"123123123125"},
{"name":"123123123126"}
];
var x1 = {}
var basicS = {
"question":[]
}
data.forEach(function(val,i){
x1[val.name]=basicS;
});
console.log(x1);
data.forEach(function(val,i){
x1[val.name].question.push('insert');
});
console.log(x1);
Output:
{
123123123123:{
question:[
0:"insert"
1:"insert"
2:"insert"
3:"insert"
]
},
123123123124:{
question:[
0:"insert"
1:"insert"
2:"insert"
3:"insert"
]
},
123123123125:{
question:[
0:"insert"
1:"insert"
2:"insert"
3:"insert"
]
},
123123123126:{
question:[
0:"insert"
1:"insert"
2:"insert"
3:"insert"
]
}
}
Expected Output should be:
{
123123123123:{
question:[
0:"insert"
]
},
123123123124:{
question:[
0:"insert"
]
},
123123123125:{
question:[
0:"insert"
]
},
123123123126:{
question:[
0:"insert"
]
}
}
Not able to understand from where four values are inserted inside the each question array while i am inserting only one in each question
array object.
Is there any alternative to solve this type of prblem.
Please help me out. I am totally confused. Thanks in advance.
You may want to create multiple objects:
data.forEach(function(val,i){
x1[val.name]={
"question":[]
};
});
Or both loops in one O(n) instead of O(2n):
data.forEach(function(val,i){
(x1[val.name]=x1[val.name] || {question:[]}).question.push(val);
});
This is happening because every value in x1 is referencing the same basicS array. So you are pushing insert into that array four times.
To avoid this, give each item in x1 a new array:
var data = [
{"name":"123123123123"},
{"name":"123123123124"},
{"name":"123123123125"},
{"name":"123123123126"}
];
var x1 = {}
data.forEach(function(val,i){
x1[val.name]= { "question": [] };
});
data.forEach(function(val,i){
x1[val.name].question.push('insert');
});
console.log(x1);
Or, depending on what you're ultimately trying to do, you could just populate the arrays with their initial value instead of looping twice:
var data = [
{"name":"123123123123"},
{"name":"123123123124"},
{"name":"123123123125"},
{"name":"123123123126"}
];
var x1 = {}
data.forEach(function(val,i){
x1[val.name] = { "question": ["insert"] };
});
console.log(x1);
Keep it simple.
Use a new object as your container to populate.
Switch from "forEach" to "for" loop to avoid confusion.
Create a new instance of the array on every iteration for reference.
Assign index at 0 to insert.Take object at iteration and set it the name property value.
Then assign to an Object with the question property set to your array at key '0'
var data = [{
"name": "123123123123"
},
{
"name": "123123123124"
},
{
"name": "123123123125"
},
{
"name": "123123123126"
}
];
var obj = {};
for (var i = 0; i < data.length; i++) {
var insert = [];
insert['0'] = 'insert';
obj[data[i].name] = {
question: insert
}
};
console.log(obj);
Related
I'm using JSEL (https://github.com/dragonworx/jsel) for search data in a huge JSON. This is an extract:
{
"Clothes":[{
"id":"clothes",
"items":[{
"shoes":[{
"sizes":{
"S":{
"cod":"S1"
},
"M":{
"cod":"M1"
},
"L":{
"cod":"L1"
}
}
}],
"pants":[{
"sizes":{
"S":{
"cod":"PS1"
},
"M":{
"cod":"PM1"
},
"L":{
"cod":"L1"
}
}
}]
}]
}]
}
If I execute this command:
var dom = jsel(data);
console.log( dom.selectAll('//#cod') );
I obtain an array with all "cod" key values from JSON:
['S1', 'M1', 'L1', 'PS1', 'PM1', 'L1']
I'm newbie on XPath expressions and I want to get the parent keys of a certain "cod" key value, for example, if "cod" key value is "S1" the result is:
"shoes"
or
"items"
or
"Clothes"
How can I get it? I'd like to receive your help
There are lot of ways available in JS. I usually prefer this kind it's more quick and reusable in any kind of objects.
You can try below snippet and you will get it more clear.
var jsonString = '{"Clothes":[{"id":"clothes", "items":[{"shoes":[{"sizes":{"S":{"cod":"S1"}, "M":{"cod":"M1"}, "L":{"cod":"L1"} } }], "pants":[{"sizes":{"S":{"cod":"PS1"}, "M":{"cod":"PM1"}, "L":{"cod":"L1"} } }] }] }] }';
const myObj = JSON.parse(jsonString);
for (let i in myObj.Clothes) {
var clothes = myObj.Clothes[i];
var clothesId = clothes.id;
var clothesItems = clothes.items;
console.log(clothesId);
var products = Object.keys(clothesItems[0])
for( var productName in products ){
var productName = products[productName];
var productSizes = clothesItems[0][productName][0].sizes;
console.log(productName);
console.log(productSizes);
}
}
I cant figure out why this arrayUnd gets repeated key values. ive been on this for three weeks. I must be doing somehthing stupid. I know they are loops. but everything works except the push. it logs when the key repeats and stuff. but it somehow is adding it to it? very confusing.
Heres my Javascript
var array = [
{"size":["12","22"]},
{"color":["blue"]},
{"design":["flower-blue"]},
{"size":["12","22","44"]},
{"color":["red"]},
{"design":["flower-blue"]}
]
//output array
arrayUnd=[
{"color":["red"]}
]
//is array?
console.log( Array.isArray(array))
function pusher(obj){
arrayUnd.push(obj)
}
function isRepeat(key,value,obj){
// console.log(key[0])
for (let item=0; item < arrayUnd.length; item++ ){
if ( arrayUnd[item].hasOwnProperty(key)){
console.log("key: " + key)
console.log("yes")
console.log(arrayUnd)
}
else{
console.log("keyno: " + key)
console.log("no")
//pusher(obj)
if ( arrayUnd[item].hasOwnProperty(key) === false){
pusher(obj)
}
console.log(arrayUnd)
}
}
}
array.forEach((obj)=>{
var a= Object.keys(obj)
var b= Object.values(obj)
isRepeat(a,b,obj)
})
console.log(arrayUnd)
Your loop is checking all objects to see if they don't match. At least one of them won't match, so it will try to push that many times. You need to check all elements, and after checking them all for existence decide if you want to push or not.
Current logic is equivalent to: if anything in arrUnd doesn't match, push me each time I check.
some works here, because it checks if anything matches, and returns true or false, which you can then use to decide if you want to push or not (only once, after I've found if anything in the array matches, deciding using the final result).
Using some to check if any other element with same key exists. Push if nothing found.
var array = [{
"size": ["12", "22"]
},
{
"color": ["blue"]
},
{
"design": ["flower-blue"]
},
{
"size": ["12", "22", "44"]
},
{
"color": ["red"]
},
{
"design": ["flower-blue"]
}
]
//output array
arrayUnd = [{
"color": ["red"]
}]
//is array?
console.log(Array.isArray(array))
function pusher(obj) {
arrayUnd.push(obj)
}
function isRepeat(key, value, obj) {
if(!arrayUnd.some(x => x.hasOwnProperty(key[0])))
arrayUnd.push(obj)
}
array.forEach((obj) => {
var a = Object.keys(obj)
var b = Object.values(obj)
isRepeat(a, b, obj)
})
console.log(arrayUnd)
You are passing an array to isRepeat instead of the key and value of the object.
Object.keys() returns an array, even if the object only has one key.
When you check if ( arrayUnd[item].hasOwnProperty(key) === false), arrayUnd[item].hasOwnProperty(key) will always be false, so the object will always get pushed to your array.
You can fix this by accessing the first key and value of each object:
array.forEach((obj)=>{
var a= Object.keys(obj)
var b= Object.values(obj)
isRepeat(a[0],b[0],obj)
})
The reason your code keeps pushing object to arrayUnd it's because when it iterates through the array it checks for the array key if its present if not it pushes it to arrayUnd, now you have 2 problems first you are not actually checking for the array key to match you comparing object so you will always get false , and second is that each time you push to the array the length of your array grow and so the number of iterations increases
you can achieve this in two lines of code
var array = [
{"size":["12","22"]},
{"color":["blue"]},
{"design":["flower-blue"]},
{"size":["12","22","44"]},
{"color":["red"]},
{"design":["flower-blue"]}
]
//output array
arrayUnd=[
{"color":["red"]}
]
array.forEach(p=>Object.entries(p).forEach(p=>{
!arrayUnd.some(o=>o.hasOwnProperty(p[0])) ? arrayUnd.push({[p[0]]:p[1]}):null
}))
console.log(arrayUnd)
var inpAry = [
{ "size": ["12", "22"] },
{ "color": ["blue"] },
{ "design": ["flower-blue"] },
{ "size": ["12", "22", "44"] },
{ "color": ["red"] },
{ "design": ["flower-blue"] }
];
var opAry = [
{ "color": ["red"] }
];
inpAry.forEach(inpAryElem => {
var ipAryElemKeys = Object.keys(inpAryElem);
var ipAryElemVals = Object.values(inpAryElem);
ipAryElemKeys.forEach((ipAryElmKey,ipAryElemKyIdx) => {
var isKeyPresent = false;
opAry.forEach(opAryElem => {
if(opAryElem[ipAryElmKey]) {
isKeyPresent = true;
opAryElem[ipAryElmKey].push(...ipAryElemVals[ipAryElemKyIdx]);
}
});
if(!isKeyPresent) {
opAry.push({[ipAryElmKey]:ipAryElemVals[ipAryElemKyIdx]});
}
})
});
console.log(opAry);
I've been trying to figure this out for a while and I just can't. I have an object, which has an array in it, which has objects in it. I'm trying to figure out how to use a for loop to search through the array's objects. Heres my attempt:
var obj = {
array: [
{"meme" : "123", "mememe" : "456"},
{"meme" : "234", "mememe" : "567"}
]
}
console.log(obj.array)
for(var i in obj) {
console.log(i);
};
This code logs the array like this:
[ { meme: '123', mememe: '456' },
{ meme: '234', mememe: '567' } ]
Then it just logs:
0
1
What I want it to log is something like
{ meme: '123', mememe: '456' }
{ meme: '234', mememe: '567' }
So I can then do something with this code.
If you only want to loop through the obj.array you can use:
for (var i = 0; i < obj.array.length; i++) {
console.log(obj.array[1]);
}
or
for (var object of obj.array) {
console.log(object);
}
or
obj.array.forEach(function(object) { console.log(object) });
if you want iterate over every array that might be in obj you can do this:
for (var property in obj) {
// gets all the propertie-names of object (in this case just 'array')
for(var object of obj[property]) {
// iterates through all the items in the array (in this case just obj['array'])
console.log(object);
}
}
You could iterate the array with a for statement and use the index for accessing the objects.
Mabye you have a look here, too: Why is using for ....in with array iteration a bad idea?
var obj = {
array: [
{ meme: "123", mememe: "456"},
{ meme: "234", mememe: "567"}
]
},
i
for (i = 0; i < obj.array.length; i++) {
console.log(obj.array[i]);
}
Here's one solution.
var obj = {
array: [
{"meme" : "123", "mememe" : "456"},
{"meme" : "234", "mememe" : "567"}
]
}
obj.array.forEach(function(item) {
console.log(item);
})
And the JSFiddle link (just turn on the dev tools (ctrl+shift+i on windows)
https://jsfiddle.net/4cn6s3tf/
I'm working in wso2 carbon dashboard. My table is containing 2 fields (Name and Number). I Have duplicate name in the objects but with different number. I want unique name with addition of numbers.
[
{
"Name":"Abc",
"number":2
},
{
"Name":"bcd",
"number":3
},
{
"Name":"Abc",
"number":5
}
]
expected output
[
{
"name":"Abc",
"Number":7
},
{
"name":"bcd",
"Number":3
}
]
I'm using java script to achieve such task. please help me
Use Array#reduce method with a reference object.
var data = [{
"Name": "Abc",
"number": 2
}, {
"Name": "bcd",
"number": 3
}, {
"Name": "Abc",
"number": 5
}];
// object for index reference
var ref = {};
// iterate and generate the array
var res = data.reduce(function(arr, o) {
// check index already defined
if (!(o.Name in ref)) {
// if not defined then define index
ref[o.Name] = arr.length;
// and push the element
// you can also use
// arr.push({Name:o.Name, number:o.number});
arr.push(Object.assign({}, o));
} else {
// if index already defined update the number
arr[ref[o.Name]].number += o.number;
}
// return the array reference
return arr;
// set initial value as empty array
}, []);
console.log(res);
I am trying to make something like this:
var Test =
{
A:function()
{
array = new Array();
array[0] = new Array("1","2","3");
array[1] = new Array("Name","Age","blabla");
},
B: function()
{
var c = new this.A();
alert(c); //output:: object Object
alert(c.array[1]); // output:: undefined
alert(c.array[1][0]); // output undefined
}
}
how can i get alerted for example alert(c.array[1][0]) with output "Name".
usually in other languages its possible to use methodes from inherited classes but in javascript. i think(hope) it's possible, but how?
Painkiller
You'd have to change A:
A:function()
{
this.array = new Array();
this.array[0] = new Array("1","2","3");
this.array[1] = new Array("Name","Age","blabla");
},
If you do change it, you'd be better to do this:
A:function()
{
this.array = [ [ "1", "2", "3" ], [ "Name", "Age", "blabla" ] ];
},
The "Array" constructor is a pretty bad API design and should be avoided.