Javascript array conversions - javascript

I have a function (that I can't change) that queries data from a database and returns it in a variable that shows as the following format if I display it as text:
var outputdata=
[
{ itemA: 'M0929', itemDate: new Date(1950,03-1,25,0,0,0,0), itemID: 'JDR12' },
{ itemA: 'X0121', itemDate: new Date(1983,07-1,07,8,0,0,0), itemID: 'RPN50' },
{ itemA: 'U0229', itemDate: new Date(1942,09-1,07,8,0,0,0), itemID: 'CRG98' },
];
I need it to be converted into the following format (specific date formatting doesn't matter) for use by another function (that I also can't change).
var inputdata=[
[
"M0929",
"1950-03-25",
"JDR12"
],
[
"X0121",
"1983-07-07",
"RPN50"
],
[
"U0229",
"1942-09-07",
"CRG98"
]
];
Could someone offer some assistance... I don't really understand javascript arrays and I'm really after a function to do the conversion.

You're probably going to have to write it yourself, for example:
function pad (what)
{
return what < 10 ? '0'+what : String(what);
}
function transformData (data)
{
var result = [];
for (var i=0;i<data.length;++i)
{
var date = data[i]['itemDate'];
result.push([
data[i]['itemA'],
date.getFullYear()+'-'+pad(date.getMonth())+'-'+pad(date.getDate()),
data[i]['itemID']
]);
}
return result;
}
var outputdata=
[
{ itemA: 'M0929', itemDate: new Date(1950,03-1,25,0,0,0,0), itemID: 'JDR12' },
{ itemA: 'X0121', itemDate: new Date(1983,07-1,07,8,0,0,0), itemID: 'RPN50' },
{ itemA: 'U0229', itemDate: new Date(1942,09-1,07,8,0,0,0), itemID: 'CRG98' },
];
var result = transformData(outputdata);
alert(result.join("\n"));
Now, the things to be aware of are the nature of UTC dates. More details can be found here http://www.w3schools.com/jsref/jsref_obj_date.asp. Also, I highly recommend reading more about Javascript in general.

function convert(outputdata){
var arr = [];
for(var i = 0; i<outputdata.length; i++){
var output = outputdata[i];
var temp = [output.itemA, output.itemDate, output.itemID];
arr[i] = temp;
}
return arr;
}
Edited: initialized arr.

Not a full response, because this smells like homework (and if it is, you should tag it as such). So hints first:
You can make an array by writing something like `[ 7, 9*7, "ho" ]
You can get at properties with dot notation like obj.itemA

Related

How to get parent keys from JSON using JSEL?

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);
}
}

Insert all properties from an object within an array to another object in array using JS/TS

I have been looking a simple way to copy/insert/move properties in an object within an array to another object. I came up with a basic logic which does the job perfectly but am not satisfied with this. There has to be a better way, any help here?
var first = [
{
"AGREE_EFF_DATE__0": "02-Aug-2018",
"AGREE_TERM_DATE__0": "30-Apr-2021",
"AGREE_IND__0": "P1",
"P_DBAR_IND__0": "N",
"AGREE_EFF_DATE__1": "01-May-2021",
"AGREE_TERM_DATE__1": null,
"AGREE_IND__1": "NP",
"P_DBAR_IND__1": "N",
"PROVIDER_SPECIALITY__0": "PSYCHOLOGY, CLINICAL",
"PROVIDER_SPECIALITY_CODE__0": "CK"
}
];
var second = [
{
"STATUS": "ACTIVE",
"MEDICARE_NUMBER" : 12345
}
];
for(let i = 0; i < second.length; i++) {
var first_keys = Object.keys(first[i]);
var first_values = Object.values(first[i]);
for(let j = 0; j < first_keys.length; j++) {
second[i][first_keys[j]] = first_values[j];
}
}
console.log(second);
//Output-
[
{
STATUS: 'ACTIVE',
MEDICARE_NUMBER: 12345,
AGREE_EFF_DATE__0: '02-Aug-2018',
AGREE_TERM_DATE__0: '30-Apr-2021',
AGREE_IND__0: 'P1',
P_DBAR_IND__0: 'N',
AGREE_EFF_DATE__1: '01-May-2021',
AGREE_TERM_DATE__1: null,
AGREE_IND__1: 'NP',
P_DBAR_IND__1: 'N',
PROVIDER_SPECIALITY__0: 'PSYCHOLOGY, CLINICAL',
PROVIDER_SPECIALITY_CODE__0: 'CK'
}
]
When possible, you should prefer iteration to manually indexed loops. This means arr.map() or arr.forEach() or arr.reduce(), to name a few.
Also, You can use an object spread to easily merge objects together.
Putting those together, you can reduce this logic to:
const result = first.map((firstObj, i) => ({ ...firstObj, ...second[i] }))
Here we map() over all members of first, which returns a new array where each member is the result of the function. This function takes the array member as the first argument, and the index of that member as the second argument. Then we can use that index to find the corresponding item in the second array.
Then you just spread both objects into a new object to assemble the final result.
var first = [
{ a: 1, b: 2 },
{ a: 4, b: 5 },
];
var second = [
{ c: 3 },
{ c: 6 },
];
const result = first.map((firstObj, i) => ({ ...firstObj, ...second[i] }))
console.log(result)
Which is all perfectly valid typescript as well.
NOTE: there is one difference between my code any yours. Your code modifies the objects in second. My code returns new objects and does not change the contents of second at all.
This is usually the better choice, but it depends on how you use this value and how data is expected to flow around your program.
You need to be careful with iterating, because you can have different count of elements in first and second arrays. So the possible solution will be like this:
const first = [
{
"AGREE_EFF_DATE__0": "02-Aug-2018",
"AGREE_TERM_DATE__0": "30-Apr-2021",
"AGREE_IND__0": "P1",
"P_DBAR_IND__0": "N",
"AGREE_EFF_DATE__1": "01-May-2021",
"AGREE_TERM_DATE__1": null,
"AGREE_IND__1": "NP",
"P_DBAR_IND__1": "N",
"PROVIDER_SPECIALITY__0": "PSYCHOLOGY, CLINICAL",
"PROVIDER_SPECIALITY_CODE__0": "CK"
}
];
const second = [
{
"STATUS": "ACTIVE",
"MEDICARE_NUMBER": 12345
}
];
console.log(mergeAll(first, second));
function mergeAll(firstArray, secondArray) {
const result = [];
const minLength = firstArray.length < secondArray.length ? firstArray.length : secondArray.length;
for (let i = 0; i < minLength; i++) {
result.push({...firstArray[i], ...secondArray[i]});
}
return result;
}

javascript how to form an array of objects by combining first Array and their values are in other arrays

Im facing a small issue in Javascript.
I have below Arrays.
var labels = ["labelOne", "labelTwo"];
var values1 = ["89", "9"];
var values2 = ["32", "78"];
Here we can place n number of values arrays like value3,value4....
Now how can i form an array of Objects by combining labels Array and their values are in values arrays. Im expecting the below output after combining above 3 arrays..
var mainArray = [{
label:"labelOne",
value:"89"
},
{
label:"labelTwo",
value:"9"
},
{
label:"labelOne",
value:"32"
},
{
label:"labelTwo",
value:"78"
}]
Can someone please help me to achieve the above output.
Thank you in advance
All that you need is a variable to know how many arrays should be added and access them in a loop using the advantage that Javascript lets you get them like this: window['variableName'] when they are defined in global scope.
var labels = ["labelOne", "labelTwo"];
var values1 = ["89", "9"];
var values2 = ["32", "78"];
var mainArray = [];
// Define a variable to know how many arrays should be added
var maxValues = 2;
function addValues(values) {
// Create new elements and push them into mainArray
mainArray.push({label:labels[0], value:values[0]});
mainArray.push({label:labels[1], value:values[1]});
}
// Do a loop from 1 to maxValues
for(let i = 1; i <= maxValues; i++) {
// Call the function with dynamic variable name
addValues(window['values' + i]);
}
console.log(mainArray);
If the order of your array isn't critical (and then, you might sort it later if it is), you can do like this:
const output = labels.map((label, index) => {
return [{ label, value: values1[index] }, { label, value: values2[index] }];
}).flat();
The map step, will give you an array like this:
[
[{ label: 'labelOne', value: 89 }, { label: 'labelOne', value: 32 }],
[{ label: 'labelTwo', value: 9}, { label: 'labelTwo', value: 78}]
]
By then calling flat, it'll transform it into:
[{ label: 'labelOne', value: 89 }, { label: 'labelOne', value: 32 }, { label: 'labelTwo', value: 9}, { label: 'labelTwo', value: 78}]
Which is what you wanted, from here you can sort the array if that matters for your use case.

Convert object to JSON Array?

I have the following object being returned. I am counting a list of names by reading from a json file and storing the results in a new object.
{
ted: 501,
jeff: 40,
tony: 90
}
The following function creates an object with the names as properties and the count as their values.
function countNames(json){
var count = {};
for (var i = 0, j = json.length; i < j; i++) {
if (count[json[i].name]) {
count[json[i].name]++;
}
else {
count[json[i].name] = 1;
}
}
return count;
}
I need to create an array of objects that generate a result like this.
[
{
name: 'ted',
total: 501
},
{
name: 'jeff',
total: 40
}
{
name: 'tony',
total: 90
}
]
I am not sure what the best approach and most efficient way of achieving this is. Any help is appreciated.
Consider this following Javascript snippet:
for (var item in obj) {
result.push({
name: item,
total: obj[item]
});
}
Working DEMO
Output:
[
{
"name":"ted",
"total":501
},
{
"name":"jeff",
"total":40
},
{
"name":"tony",
"total":90
}
]
I don't understand how your code example relates to the question, but this turns the data in the first format into the last format:
var output = Object.keys(input).map(function(key) {
return {
name: key,
count: input[key]
}
});
it uses functional programming style, which usually leads to cleaner code.
JSBin

Flattening an array of objects into another array of objects using javascript

I've come up against this issue in multiple contexts and languages and I always been able to work around it but I'd like to finally figure out a proper pattern to handle this. It comes from joining SQL tables. Usually I would make two calls, one for items and one for comments but I know there's a way to get it all in one call and then flatten the result.
What I'd like to do is to take an array that looks like this:
[
{
itemId: 1,
comments: {
commentId: 1
}
},
{
itemId: 1,
comments: {
commentId: 2
}
},
{
itemId: 2,
comments: {
commentId: 3
}
}
]
And turn it into this:
[
{
itemId: 1,
comments: [
{
commentId: 1
},
{
commentId: 2
}
]
},
{
itemId: 2,
comments: [
{
commentId: 3
}
]
}
]
The following should work for you:
function combine(arr) {
var newObj = {};
// combine the comments
for (var i=0; i < arr.length; i++) {
if (newObj[arr[i].itemId]) {
newObj[arr[i].itemId].push(arr[i].comments);
} else {
newObj[arr[i].itemId] = [arr[i].comments];
}
}
// make the list
var keys = Object.keys(newObj);
return keys.map(function(key){return {itemId: key, comments: newObj[key]} })
}
Also you can use filter():
function combine(src) {
var dict = {};
return src.filter(function(item) {
if (!dict[item.itemId]) {
item.comments = [ item.comments ];
dict[item.itemId] = item;
return true;
} else {
dict[item.itemId].comments.push(item.comments);
return false;
}
});
}

Categories

Resources