Json - create an ID column that auto increment - javascript

I'm building a json object from 2 dataset and I need to add a column (ID) with a unique value,
I have thought that having an auto increment ID (1,2,3,4..) value will be great
This is how I'm building my Json object with JavaScript
var output = [];
for (var rowIdx = 0; rowIdx < csv.length; rowIdx++) {
var row = {};
for (var fieldIdx =0; fieldIdx < fields.length; fieldIdx++) {
var field = editor.field( fields[fieldIdx] );
var mapped = data[ field.name() ];
row[field.name()] = csv[rowIdx][mapped];
}
output.push(row);
}
var json = JSON.stringify(output);
console.log(json)
and this is my JSON: PLEASE NOTE: I want to add "id": "1" column whose value will auto increment for each record
[
{
"id": "1", <--- DESIRED
"title": "Hello World",
"artist": "John Smith",
"genre": "pop",
"week": "4",
"highest_rating": "3",
"year": "2014",
"youtube": "www"
]
},
{
"id": "2", <--- DESIRED
"title": "Lorem Ipsum",
"artist": "John Smith",
"genre": "pop",
"week": "4",
"highest_rating": "3",
"year": "2014",
"youtube": "www"
]
}
]

you can do this row.id = (rowIdx + 1);
var output = [];
for (var rowIdx = 0; rowIdx < csv.length; rowIdx++) {
var row = {};
for (var fieldIdx = 0; fieldIdx < fields.length; fieldIdx++) {
var field = editor.field(fields[fieldIdx]);
var mapped = data[field.name()];
row[field.name()] = csv[rowIdx][mapped];
}
row.id = (rowIdx + 1); // <--- this line
output.push(row);
}
var json = JSON.stringify(output);
console.log(json);

You can increment an i number starting from 0, for Id of each object in the output array. For example:
for(let i=0; i<output.length; i++)
{ output[i].id=i+1;}

Related

How does `lookupIndex[row[lookupKey]] = row;` work?

I am reading learnjsdata.com and came across this unfamiliar JavaScript syntax. The syntax is as follows:
lookupIndex[row[lookupKey]] = row;
Anyone know what's happening here? I haven't seen syntax like this. Used in context:
Data
var articles = [{
"id": 1,
"name": "vacuum cleaner",
"weight": 9.9,
"price": 89.9,
"brand_id": 2
}, {
"id": 2,
"name": "washing machine",
"weight": 540,
"price": 230,
"brand_id": 1
}, {
"id": 3,
"name": "hair dryer",
"weight": 1.2,
"price": 24.99,
"brand_id": 2
}, {
"id": 4,
"name": "super fast laptop",
"weight": 400,
"price": 899.9,
"brand_id": 3
}];
var brands = [{
"id": 1,
"name": "SuperKitchen"
}, {
"id": 2,
"name": "HomeSweetHome"
}];
Function & Invocation
function join(lookupTable, mainTable, lookupKey, mainKey, select) {
var l = lookupTable.length,
m = mainTable.length,
lookupIndex = [],
output = [];
for (var i = 0; i < l; i++) { // loop through l items
var row = lookupTable[i];
lookupIndex[row[lookupKey]] = row; // create an index for lookup table
}
for (var j = 0; j < m; j++) { // loop through m items
var y = mainTable[j];
var x = lookupIndex[y[mainKey]]; // get corresponding row from lookupTable
output.push(select(y, x)); // select only the columns you need
}
return output;
};
var result = join(brands, articles, "id", "brand_id", function(article, brand) {
return {
id: article.id,
name: article.name,
weight: article.weight,
price: article.price,
brand: (brand !== undefined) ? brand.name : null
};
});
console.log(result);
Appreciate any answers or pointers, thanks!
Think of it as two separate function calls:
var rowLookup = row[lookupKey];
lookupIndex[rowLookup] = row;
It's the same as doing it all in the same line:
lookupIndex[row[lookupKey]] = row;

Accessing data in JS structure

I'm trying to parse the following data:
data = [
{"id":"orderBy", "options" : [
{"value":"order-by=newest&", "name":"newest"},
{"value":"order-by=relevance&", "name":"relevance"}
]},
{"id":"searchBy", "options" : [
{"value":"search-by=name&", "name":"name"},
{"value":"search-by=number&", "name":"number"},
{"value":"search-by=date&", "name":"date"},
{"value":"search-by=location&", "name":"location"}
]}
];
Using this data I want to iterate through each object and return its ID, and then all of it options.
I know I need to use for loop like this:
for (var i =0; i < data.length; i++) {
var id = data[i].id;
var optionText = data[i].options[i].text;
var optionValue = data[i].options[i].value;
console.log(id);
console.log(optionText);
console.log(optionValue);
}:
This loop only returns the first OptionText & OptionValue from the data. Can you teach me what I'm doing wrong?
Thanks.
You could use another for loop for the inner array.
var data = [{ "id": "orderBy", "options": [{ "value": "order-by=newest&", "name": "newest" }, { "value": "order-by=relevance&", "name": "relevance" }] }, { "id": "searchBy", "options": [{ "value": "search-by=name&", "name": "name" }, { "value": "search-by=number&", "name": "number" }, { "value": "search-by=date&", "name": "date" }, { "value": "search-by=location&", "name": "location" }] }],
i, j, id, optionText, optionValue;
for (i = 0; i < data.length; i++) {
id = data[i].id;
for (j = 0; j < data[i].options.length; j++) {
optionText = data[i].options[j].name;
optionValue = data[i].options[j].value;
console.log(id, optionText, optionValue);
}
}
data = [
{"id":"orderBy", "options" : [
{"value":"order-by=newest&", "name":"newest"},
{"value":"order-by=relevance&", "name":"relevance"}
]},
{"id":"searchBy", "options" : [
{"value":"search-by=name&", "name":"name"},
{"value":"search-by=number&", "name":"number"},
{"value":"search-by=date&", "name":"date"},
{"value":"search-by=location&", "name":"location"}
]}
];
for (var i in data) {
var id = data[i].id;
console.log(id)
for (var opt of data[i].options){
console.log(opt.value);
console.log(opt.name)
}
}
You lacked an interation loop. Also I believe it could be the perfect example for you to see the difference (and existence?) of iterating through objects and arrays with in and of
You have two levels of arrays you need to loop through. First loop through the outer array, and then through the options of each item:
var data = [{"id":"orderBy","options":[{"value":"order-by=newest&","name":"newest"},{"value":"order-by=relevance&","name":"relevance"}]},{"id":"searchBy","options":[{"value":"search-by=name&","name":"name"},{"value":"search-by=number&","name":"number"},{"value":"search-by=date&","name":"date"},{"value":"search-by=location&","name":"location"}]}];
for (var i = 0; i < data.length; i++) {
var id = data[i].id;
console.log(id);
for(var j = 0; j < data[i].options.length; j++) {
var optionText = data[i].options[j].name;
var optionValue = data[i].options[j].value;
console.log(optionText);
console.log(optionValue);
}
}

How to parse nested JSON in Javascript?

I am trying to parse and show JSON data (product catalog) using XMLHttpRequest method. I am able to display the brands and their names, but not able to showcase list of products progmatically.
Here is the sample JSON request:
{
"products": {
"laptop": [{
"brand": "sony",
"price": "$1000"
}, {
"brand": "acer",
"price": "$400"
}],
"cellphone": [{
"brand": "iphone",
"price": "$800"
}, {
"brand": "htc",
"price": "$500"
}],
"tablets": [{
"brand": "iPad",
"price": "$800"
}, {
"brand": "htc-tab",
"price": "$500"
}]
}
}
Right now I am using following code to show data in tabluar form:
function loadJSON() {
var data_file = "http://localhost/AJAX/productcatalog.json";
var http_request = new XMLHttpRequest();
http_request.onreadystatechange = function () {
if ((http_request.readyState == 4) && (http_request.status == 200)) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
data = '<table border="2"><tr><td>Type</td><td>Brand</td><td>Price</td></tr>';
var i = 0;
debugger;
for (i = 0; i < jsonObj["products"].laptop.length; i++)
{
obj = jsonObj["products"].laptop[i];
data = data + '<tr><td>laptop</td><td>' + obj.brand + '</td><td>' + obj.price + '</td></tr>';
}
for (i = 0; i < jsonObj["products"].cellphone.length; i++)
{
obj = jsonObj["products"].cellphone[i];
data = data + '<tr><td>laptop</td><td>' + obj.brand + '</td><td>' + obj.price + '</td></tr>';
}
for (i = 0; i < jsonObj["products"].tablets.length; i++)
{
obj = jsonObj["products"].tablets[i];
data = data + '<tr><td>laptop</td><td>' + obj.brand + '</td><td>' + obj.price + '</td></tr>';
}
data += '</table>';
document.getElementById("demo").innerHTML = data;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
Question What is the way to fetch product list , i.e. products, cellphone and tablets ? Right now I have hardcoded that in order to fetch complete list of brands. Please advice. (I want to use plain javascript and not jquery)
Thanks!
It sounds like what you're missing is the "How do I iterate over an object when I don't know all the keys".
An object is a set of key, value pairs. You can use for/in syntax: for( var <key> in <object> ){} to get each key.
For your use case it might be something like:
var products = jsonObject['products'];
for( var productName in products ){
//productName would be "laptop", "cellphone", etc.
//products[productName] would be an array of brand/price objects
var product = products[productName];
for( var i=0; i<product.length; i++ ){
//product[i].brand
//product[i].price
}
}
In practice, I might use something a little less verbose, but this makes it easier to understand what is going on.
To achieve the expected i have used for loop and HTML DOM createElement() Method
var product_catalog = {
"products": {
"laptop": [{
"brand": "sony",
"price": "$1000"
}, {
"brand": "acer",
"price": "$400"
}],
"cellphone": [{
"brand": "iphone",
"price": "$800"
}, {
"brand": "htc",
"price": "$500"
}],
"tablets": [{
"brand": "iPad",
"price": "$800"
}, {
"brand": "htc-tab",
"price": "$500"
}]
}
};
var output = document.querySelector('#product tbody');
function build(JSONObject) {
/**get all keys***/
var keys = Object.keys(JSONObject);
/**get all subkeys***/
var subkeys = Object.keys(JSONObject[keys]);
console.log(subkeys);
/**loop sub keys to build HTML***/
for (var i = 0, tr, td; i < subkeys.length; i++) {
tr = document.createElement('tr');
td = document.createElement('td');
td.appendChild(document.createTextNode(subkeys[i]));
tr.appendChild(td);
output.appendChild(tr);
}
};
build(product_catalog);
HTML:
Coepen URL for reference- http://codepen.io/nagasai/pen/xOOqMv
Hope this works for you :)
Look at this example:
var x = data.key1.children.key4;
var path = "data";
function search(path, obj, target) {
for (var k in obj) {
if (obj.hasOwnProperty(k))
if (obj[k] === target)
return path + "['" + k + "']"
else if (typeof obj[k] === "object") {
var result = search(path + "['" + k + "']", obj[k], target);
if (result)
return result;
}
}
return false;
}
//Then for evry node that you need you can call the search() function.
var path = search(path, data, x);
console.log(path); //data['key1']['children']['key4']
I think this is what you're asking about, you can use Object.keys to get the properties of an object, then loop through them afterward.
var data = {
"products": {
"laptop": [{
"brand": "sony",
"price": "$1000"
}, {
"brand": "acer",
"price": "$400"
}],
"cellphone": [{
"brand": "iphone",
"price": "$800"
}, {
"brand": "htc",
"price": "$500"
}],
"tablets": [{
"brand": "iPad",
"price": "$800"
}, {
"brand": "htc-tab",
"price": "$500"
}]
}
}
var typesOfProducts = Object.keys(data.products)
console.log(typesOfProducts)
document.getElementById('output').textContent = typesOfProducts.toString()
//Then, to loop through
var i = -1,
len = typesOfProducts.length
function handleProduct(productType) {
console.log("This is the " + productType + " data.")
console.log(data.products[productType])
}
while (++i < len) {
handleProduct(typesOfProducts[i])
}
<div id="output"></div>
It sounds like what you're looking for is just an array of the keys of the "products" object. Example:
Products: ["laptop", "cellphone", "tablets"];
If so, I would just run your json object through javascript's Object.keys() method.
var jsonObj = JSON.parse(http_request.responseText);
var products = Object.keys(jsonObj.products);
// products = ["laptop", "cellphone", "tablets"];

Push Unique Objects to JavaScript Array

How do I push an object into an specified array that only updates that array? My code pushes an object and updates all arrays, not just the specified one.
Here is the structure of the data:
{
"d": {
"results": [
{
"Id": 1,
"cost": "3",
"item": "Project 1",
"fiscalyear": "2014",
"reportmonth": "July"
}
]
}
}
Here is a sample of the desired, wanted results:
{
"Project 1": [
{
"date": "31-Jul-14",
"rating": "3"
},
{
"date": "31-Aug-14",
"rating": "4"
}
],
"Project 2": [
{
"date": "31-Jul-14",
"rating": "2"
}
]
}
This is my attempt:
var results = data.d.results;
var date;
var projectObj = {},
projectValues = {},
project = '';
var cost = '',
costStatus = '';
for (var i = 0, m = results.length; i < m; ++i) {
project = results[i]['item'];
if (!projectObj.hasOwnProperty(project)) {
projectObj[project] = [];
}
// use Moment to get and format date
date = moment(new Date(results[i]['reportmonth'] + ' 1,' + results[i]['fiscalyear'])).endOf('month').format('DD-MMM-YYYY');
// get cost for each unique project
costStatus = results[i]['cost'];
if (costStatus == null || costStatus == 'N/A') {
cost = 'N/A';
}
else {
cost = costStatus;
}
projectValues['rating'] = cost;
projectValues['date'] = date;
projectObj[project].push(projectValues);
}
Here is a Fiddle with the undesired, unwanted results:
https://jsfiddle.net/yh2134jn/4/
What am I doing wrong?
That is because You do not empty it new iteration. Try this:
for (var i = 0, m = results.length; i < m; ++i) {
projectValues = {};
project = results[i]['item'];
....
}

JSON to filtered Array in JavaScript

I have this JSON string:
[
{
"pk": "alpha",
"item": [{
"child": "val"
}]
},
{
"pk": "beta",
"attr": "val",
"attr2": [
"child1"
]
},
{
"pk": "alpha",
"anotherkey": {
"tag": "name"
}
}
]
And I need to produce a filtered array without repeated PK, in the example above the last entry: "pk": "alpha","anotherkey": { ... should be eliminated from the output array. All this using JavaScript. I tried with the object JSON.parse but it returns many key,value pairs that are hard to filter for example "key=2 value=[object Object]".
Any help is greatly appreciated.
var data = JSON.parse(jsonString);
var usedPKs = [];
var newData = [];
for (var i = 0; i < data.length; i++) {
if (usedPKs.indexOf(data[i].pk) == -1) {
usedPKs.push(data[i].pk);
newData.push(data[i]);
}
}
// newData will now contain your desired result
var contents = JSON.parse("your json string");
var cache = {},
results = [],
content, pk;
for(var i = 0, len = contents.length; i < len; i++){
content = contens[i];
pk = content.pk;
if( !cache.hasOwnPropery(pk) ){
results.push(content);
cache[pk] = true;
}
}
// restuls
<script type="text/javascript">
// Your sample data
var dataStore = [
{
"pk": "alpha",
"item": [{
"child": "val"
}]
},
{
"pk": "beta",
"attr": "val",
"attr2": [
"child1"
]
},
{
"pk": "alpha",
"anotherkey": {
"tag": "name"
}
}
];
// Helper to check if an array contains a value
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
// temp array, used to store the values for your needle (the value of pk)
var tmp = [];
// array storing the keys of your filtered objects.
var filteredKeys = [];
// traversing you data
for (var i=0; i < dataStore.length; i++) {
var item = dataStore[i];
// if there is an item with the same pk value, don't do anything and continue the loop
if (tmp.contains(item.pk) === true) {
continue;
}
// add items to both arrays
tmp.push(item.pk);
filteredKeys.push(i);
}
// results in keys 0 and 1
console.log(filteredKeys);
</script>

Categories