Create an array of array - javascript

I have the following array
var a = ["Banana/hgd/kjjkds", "Orange/kldj/kdl",
"Apple/jlds/ldks", "Mango/dsfj/dskj"]
Now I want to re-create it as below and make the output
{
"a1" : "Banana",
"a2" : "hgd",
"a3" : "kjjkds"
}
{
"a1" : "Orange",
"a2" : "kldj",
"a3" : "kdl"
}
{
"a1" : "Apple",
"a2" : "jlds",
"a3" : "ldks"
}
{
"a1" : "Mango",
"a2" : "dsfj",
"a3" : "dskj"
}
I tried the following method but without any success:
var b = [];
for (var i = 0; i< a.length; i++) {
b['a1'] = a[i].split("/")[0];
b['a2'] = a[i].split("/")[1];
b['a3'] = a[i].split("/")[2];
console.log(b);
b.push(b);
}
The console prints all the array created but the array b only shows the last one. How can i get it to work? Please help.

try this:
var spl, b = [];
for (var i = 0, len = a.length; i < len; i++) {
spl = a[i].split("/"); /* execute split() just once */
b[i] = {
'a1': spl[0],
'a2': spl[1],
'a3': spl[2]
}
}
console.log(b);

You are pushing the array onto itself. That should set off warning signals.
Instead, you need an output array, and a temporary array to add the keys to.
var b = [], t, s, l = a.length, i;
for( i=0; i<l; i++) {
s = a[i].split("/");
t = {
"a1":s[0],
"a2":s[1],
"a3":s[2]
}
b.push(t);
}
I've also added a couple of optimisations in there.

Related

Count and loop through JSON object of arrays

I get issues when I want to loop through a JSON array of objects.
Issues such as:
It only counts two (I assume because of they Object.keys) and I have two keys.
Loops with only one value
My code:
var codes = require('./nl.json');
for (var i = 0, l = Object.keys(codes).length; i <= l; i++) {
console.log(l) ;
var areaCodeTest = codes.netherlands[i].areaCode;
var areaNameTest = codes.netherlands[i].areaName;
it("Search for postal code ", function(){
var postCode = element(by.id("imysearchstring"));
postCode.click();
browser.sleep(1000);
console.log(areaCodeTest);
postCode.clear().sendKeys(areaCodeTest);
browser.sleep(1000);
console.log("Typed " + areaCodeTest);
});
}
My Json (Short example):
{
"netherlands": [
{
"areaCode": 9401,
"areaName": "Assen"
},
{
"areaCode": 9402,
"areaName": "Assen"
},
{
"areaCode": 9403,
"areaName": "Assen"
}
]
}
I have looked at answers such as :
Size of Object and
Length of Json
I have tried:
(var i = 0, l = Object.keys(codes).length; i <= l; i++)
(var i = 0, l = Object.keys(codes.netherlands[0]).length; i <= l; i++)
for (var i = 0, l = codes.netherlands.length; i <= l; i++) // uses last areaCode in json file and only loop with that number. It does not start from top.
Image:
some of my outputs
Expected:
What I want is to count amount of ofjects in JSON (Not the key/values)
Loop through all data and assign them to var areaCodeTest = codes.netherlands[i].areaCode; and var areaNameTest = codes.netherlands[i].areaName;
I got it to work by using the following:
var codes = require('./nl.json');
codes.forEach((item) => {
var areaCodeTest = item.areaCode;
var areaNameTest = item.areaName;
it("and search for postal code ", function(){
var postCode = element(by.id("imysearchstring"));
postCode.click();
console.log(areaCodeTest);
postCode.clear().sendKeys(areaCodeTest);
browser.sleep(1000);
console.log("Typed " + areaCodeTest);
});
}
I am not a 100% what the => means near the foreach but I am currently researching why my code works. If you know please post a comment so that other developers also learn.
This let me think of the meme "not sure why code does not work / Not sure why code works"
You need to access the actual key in your loop in order to access codes[key]
Simplified version of your for() loop with stored variable for the object keys or using for in loop
const keys = Object.keys(codes)
for (let i = 0; i < keys.length; i++) {
// current object key and value of that property in main object
const key = keys[i], arr = codes[key];
console.log(`key = ${key}, length= ${arr.length}`)
// do another loop here for `arr` if needed
}
// OR using `for in`
for (let key in codes) {
console.log(`key = ${key}, length= ${codes[key].length}`)
}
<script>
const codes = {
"netherlands": [{
"areaCode": 9401,
"areaName": "Assen"
},
{
"areaCode": 9402,
"areaName": "Assen"
},
{
"areaCode": 9403,
"areaName": "Assen"
}
]
}
</script>
Try this I give you a sample
const object1 = {
a: 'somestring',
b: 42,
c: false
};
var length = (Object.keys(object1).length);
Please Refer this Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Javascript returns only keys but not values

The following is the data from the source file:
{
"dubbuseqchapter+block#a7a5931f68d0482eaff2b7c9f9684e47": {
"category": "chapter",
"children": [
"dubbuseqsequential+block#968513c8f0cc4249b7cfc2290ac967dc",
"dubbuseqsequential+block#f7f730a478144a74bd127f996d6dc4f5",
"dubbuseqsequential+block#91a0d5d7cd9649a3bdf057400e0a1c96",
"dubbuseqsequential+block#28b2b171b6734b13af29735796c5ad5a",
"dubbuseqsequential+block#192a150c8aab43b9bd236773ba60b414",
"dubbuseqsequential+block#26b3464dad42460ea66f9afe89770065"
],
"metadata": {
"display_name": "Introduction course orientation"
}
},
"dubbuseqchapter+block#b2451e9195c5466db8b66f53ed06c9fd": {
"category": "chapter",
"children": [
"dubbuseqsequential+block#c95826a16f71405ba58319d23d250fc4",
"dubbuseqsequential+block#fe4e3b8b7cdd4fa0b9fe9090223b7125",
"dubbuseqsequential+block#44bbdee625dc465ebe725d2126ed0662",
"dubbuseqsequential+block#8d4daba07d4443f3b2a0b2506280ee2c",
"dubbuseqsequential+block#c68d9d3ba7de45b1b0770085e4f1f286",
"dubbuseqsequential+block#ccdca5b2aca94dbdabb3a57a75adf3fa"
],
"metadata": {
"display_name": "Module closing section"
}
}
}
The following javascript brings the top key values (i.e dubbuseqchapter+block#a7a5931f68d0482eaff2b7c9f9684e47,dubbuseqchapter+block#b2451e9195c5466db8b66f53ed06c9fd )
Javascript code
var obj = JSON.parse(jContent);
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var row = createRowCopy(getOutputRowMeta().size());
var idx = getInputRowMeta().size();
row[idx++] = keys[i];
// Alert (keys.length);
putRow(row);
}
However, I am unable to get the values of the keys..(i.e. Category, Children and metadata) in this example.
I have tried Objects.values() but it returns null or object object in the Alert.
keys is an array of strings, each string being a property name.
You get the value for a property name in the usual way:
object[property_name]
i.e.
var value = obj[keys[i]];
this code shows how to navigate into parsed JsonData
var obj = JSON.parse(textJson);
var keys = Object.keys(obj);
console.log(obj[keys[0]].metadata.display_name);
this will print : Introduction course orientation
Or even this way to retrieve your subProperties
var obj = JSON.parse(textJson);
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++){
console.log(keys[i]);
var subKeys = Object.keys(obj[keys[i]]);
for (var j = 0; j < subKeys.length; j++) console.log(subKeys[j] + " --> " + obj[keys[i]][subKeys[j]]);
}

Join same properties value from Objects

I have an array of object, I want to know the best way of concatenating values from similar properties e.g.
arr:[
{obj:{obj_type:1, obj_foo:"joe"}},
{obj:{obj_type:2, obj_foo:"developer"}},
{obj:{obj_type:1, obj_foo:"kevin"}},
{obj:{obj_type:2, obj_foo:"architect"}}
]
I need to concatenate properties value of same obj_type property.
expected result should be:
arr:[
{obj:{obj_type:1, obj_foo:"joe|kevin"}},
{obj:{obj_type:2, obj_foo:"developer|architect"}}
]
i.e. values are concatenated based on obj_type.
I think code like this might be helpful for you:
//Objects to work with:
var arr = [{obj:{obj_type:1, obj_foo:"joe"}},
{obj:{obj_type:2, obj_foo:"developer"}},
{obj:{obj_type:1, obj_foo:"kevin"}},
{obj:{obj_type:2, obj_foo:"architect"}}];
//Map from obj_type to {obj: …} objects:
var map = {};
//Iterating arr:
for(var i = 0; i < arr.length; i++){
var o = arr[i], type = o.obj.obj_type;
if(type in map){
map[type].obj.obj_foo += '|' + o.obj.obj_foo;
}else{
map[type] = o;
}
}
//Putting map values to arr:
arr = [];
for(var key in map){
arr.push(map[key]);
}
//Done:
console.log(arr);
Produced output looks like this:
[ { obj: { obj_type: 1, obj_foo: 'joe|kevin' } },
{ obj: { obj_type: 2, obj_foo: 'developer|architect' } } ]
This variant doesn't change content of initial array.
var types = {};
var newArr = [];
var type, newObj;
for ( var i = 0; i < arr.length; ++i ) {
type = arr [ i ].obj.obj_type;
if ( type in types ) {
types[ type ].obj.obj_foo += '|' + arr[ i ].obj.obj_foo;
} else {
newObj = {
obj: {
obj_type: arr[ i ].obj.obj_type,
obj_foo: arr[ i ].obj.obj_foo
}
};
types[ type ] = newObj;
newArr.push( newObj );
}
}
return newArr; // result array
This might be the simplest approach:
// Your array
var arr = [
{obj:{obj_type:1, obj_foo:"joe"}},
{obj:{obj_type:2, obj_foo:"developer"}},
{obj:{obj_type:1, obj_foo:"kevin"}},
{obj:{obj_type:2, obj_foo:"architect"}}
];
// Loop over all elements
for(var i = 0; i < arr.length; i++) {
var a = arr[i].obj;
// Compare to each other element
for(var j = i + 1; j < arr.length; j++) {
var b = arr[j].obj;
// If the obj_type is equal...
if(a.obj_type === b.obj_type) {
// Merge data...
a.obj_foo += '|' + b.obj_foo;
// Remove other element
arr.splice(j--, 1);
}
}
}
Output (from node.js):
[ { obj: { obj_type: 1, obj_foo: 'joe|kevin' } },
{ obj: { obj_type: 2, obj_foo: 'developer|architect' } } ]

How to extract total instance of a variable in a array and its first properties

I have got a fruits array as shown below
var fruits = [
{
"buyprice": "10",
"sellprice": "11",
"name": "pomogranate"
},
{
"buyprice": "10",
"sellprice": "11",
"name": "apple"
},
{
"buyprice": "12",
"sellprice": "13",
"name": "orange"
},
{
"buyprice": "14",
"sellprice": "15",
"name": "apple"
}
]
I want to find out the total counts of apple present in the array
and the buy price and sellprice of the first element of the apple present in the array (not the last element)
I have tried it this way
function findnumberofaccourences(fruits, apple) {
var a = 0;
var buyprice;
var sellprice
for (var i = 0; i < fruits.length; i++) {
var name = fruits[i].name;
buyprice = fruits[i].buyprice;
sellprice = fruits[i].sellprice;
if (name == apple) {
a++;
}
}
var p = { count: a, buyprice: buyprice, sellprice: sellprice };
return p;
}
var result = findnumberofaccourences(fruits, 'apple');
alert(JSON.stringify(result));
But when i run this i am getting the result as (the buyprice and sellprice of apple's last element , where as i need apples first element )
{"count":2,"buyprice":"14","sellprice":"15"}
This is my fiddle
http://jsfiddle.net/thkc0fpk/2/
could you please elt em know how to achive this
A few things:
As Hacketo said, only grab the prices when a == 0.
Also, only grab the price for apples, rather than all fruit.
Calling the argument giving the fruit name to find apple is a bit misleading (since it could contain the string pear). Perhaps fruitName or similar instead?
Here's a minimal-changes example:
function findnumberofaccourences(fruits, fruitName) {
var a = 0;
var buyprice;
var sellprice;
for (var i = 0; i < fruits.length; i++) {
var name = fruits[i].name;
if (name == fruitName) { // Only apples
if (a == 0) { // Only the first
buyprice = fruits[i].buyprice;
sellprice = fruits[i].sellprice;
}
a++;
}
}
var p = {
count: a,
buyprice: buyprice,
sellprice: sellprice
};
return p;
}
var result = findnumberofaccourences(fruits, 'apple');
alert(JSON.stringify(result));
You can also simplify a fair bit, using the more-modern forEach and using the object you're going to return directly:
function findnumberofaccourences(fruits, fruitName) {
var p = {
count: 0,
buyprice: undefined,
sellprice: undefined
};
fruits.forEach(function(fruit) {
if (fruit.name == fruitName) {
if (p.count == 0) {
p.buyprice = fruit.buyprice;
p.sellprice = fruit.sellprice;
}
p.count++;
}
});
return p;
}
var result = findnumberofaccourences(fruits, 'apple');
alert(JSON.stringify(result));
You can filter apples first into an array, then retrieve the first element of this array to get the data you need.
var apples = fruits.filter(function (fruit) {
return fruit.name === 'apple';
});
var p = {
count: apples.length,
buyprice: apples[0].buyprice,
sellprice: apples[0].sellprice
};
Just reverse the array first
var price = {
count: 0
};
fruits.reverse().forEach(function (fruit) {
if (fruit.name === "apple") {
price.count++;
price.buyprice = fruit.buyprice;
price.sellprice = fruit.sellprice;
}
})
console.log(price)
// restore original order in fruits array (if you are going to use it)
fruits.reverse();
Note that this will reverse your array in place, so you'll need to do a fruits.reverse() once again to get back the fruits array elements in the original order, if you are going to use fruits further down the flow. (Thanks aduch)
Well your code does not work as you expect, your example work only because apple is the last element of the array.
you need to update your for loop like this
for (var i = 0; i < fruits.length; i++) {
var name = fruits[i].name;
if (name == apple) {
if ( a === 0){
buyprice = fruits[i].buyprice;
sellprice = fruits[i].sellprice;
}
a++;
}
}
It will update buyprice and sellprice only the first time for the first apple
Your orignal code was updating buyprice and sellprice for each element of your array

browse a table and share it on 2 tables in javascript

I have a table that follows a defined sequence that Repite : [ col , name , value1, value2 , value 3, col, name value1, value2, value3 ..col , name , value1, value2 , value 3 ]
code:
var data =["DN","Atac","1","2","3","PDA","Atac","5","6","7","EPDA","Atac","8","9","11","DN Potentielle","Atac","14","4","8"] ;
I try to split the data table col , name , values:
Code result :
var column = ["DN","PDA","EPDA","DN Potentielle"];
var name ="Atac";
var values =[ "1","2","3","5","6","7","8","9","11","14","4","8"];
how has the simplest method without a lot of code to do it
If you're sure that your data is consistent and can rely on the structure you wrote, the simplest thing would be:
var column = [];
var name = [];
var values = [];
for (var i = 0; i < data.length; i = i+5) {
column.push(data[i]);
name.push(data[i+1]);
values.push(data[i+2]);
values.push(data[i+3]);
values.push(data[i+4]);
};
name = name.filter(function(value, index, self) {
return self.indexOf(value) === index;
});
console.log(column); //["DN","PDA","EPDA","DN Potentielle"]
console.log(name); //["Atac"]
console.log(values); //["1", "2", "3", "5", "6", "7", "8", "9", "11", "14", "4", "8"]
Fiddle
Set up an object to hold the values:
var obj = { column: [], name: null, values: [] };
Then cycle over the array in groups of 5, adding the various elements to the object:
for (var i = 0, l = data.length; i < l; i+=5) {
obj.column.push(data[i]);
obj.name = data[i + 1];
// push.apply is a neat way of concatenation that doesn't
// require the creation of a new variable
obj.values.push.apply(obj.values, data.slice(i + 2, i + 5));
}
DEMO
I try to figure out what you want, and the best way is to retrieve the number value and string value without spliting it.
var data =["DN","Atac","1","2","3","PDA","Atac","5","6","7","EPDA","Atac","8","9","11","DN Potentielle","Atac","14","4","8"] ;
var columns = [];
var values = [];
$.each(data, function(k, v) {
var parsedValue = parseInt(data[k]);
if ( ! isNaN(parsedValue) ) {
values.push(parsedValue);
} else {
columns.push(v);
}
});
console.log(columns);
console.log(values);
Demo: http://jsfiddle.net/bzryqs84/1/

Categories

Resources