Related
I need to build a map "A" from an existing array of objects. However the key value pairs on Map A are from the values of existing Object keys "id" and "cap".
Is it possible to read the values of 2 keys and store as an object
var items = [{
"id": 1,
"name": "Primary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}]
},{
"id": 2,
"name": "Secondary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}
]
}]
My map needs to be like this
{ "1" : [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}],
"2" : [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}]
}
Use Array#reduce to achieve the results like below:
var items = [{
"id": 1,
"name": "Primary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}]
}, {
"id": 2,
"name": "Secondary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}]
}];
var ans = items.reduce(function(v, i) {
v[i.id] = i.cap;
return v;
}, {});
console.log(ans);
You can do this using a simple loop on the original array, and defining a new key: value pair into the object.
// Create the map
var map = {}
// For every 'item' within the 'items' array
items.forEach(item => {
// Map the item ID to the item.cap array
map[item.id] = item.cap
}
var items = [{
"id": 1,
"name": "Primary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}]
}, {
"id": 2,
"name": "Secondary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}]
}]
var map = {}
items.forEach(item => {
map[item.id] = item.cap
})
console.log(map)
Using ES6 Array.from() method.
var items = [{
"id": 1,
"name": "Primary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}]
},{
"id": 2,
"name": "Secondary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}
]
}];
var obj = {};
var res = Array.from(items, x => obj[x.id] = x.cap);
console.log(obj);
I have a json array and i need to delete the subarray whose id value is 5, which is falling under the serialNo 1. I tried the following method, but its not deleting any entry in the subarray.
let Details = [
{ "serialNo": "1", "text": "AAA", "subArray": [{ "id": "1", "name": "geo" }, { "id": "5", "name": "gau" }, { "id": "4", "name": "joi" }] },
{ "serialNo": "2", "text": "BBB", "subArray": [{ "id": "7", "name": "rom" }, { "id": "5", "name": "dom" }, { "id": "4", "name": "noi" }] },
{ "serialNo": "3", "text": "CCC", "subArray": [{ "id": "1", "name": "glo" }, { "id": "5", "name": "gum" }, { "id": "4", "name": "lom" }] }
];
Details.map((data) => {
if (data.serialNo === "1") {
data.subArray.map((subDetails) => {
if (subDetails.id === "5") {
delete data.subArray[subDetails];
}
})
}
})
I don't know why you explicitely wants to use the map function. But the following works:
let Details = [
{ "serialNo": "1", "text": "AAA", "subArray": [{ "id": "1", "name": "geo" }, { "id": "5", "name": "gau" }, { "id": "4", "name": "joi" }] },
{ "serialNo": "2", "text": "BBB", "subArray": [{ "id": "7", "name": "rom" }, { "id": "5", "name": "dom" }, { "id": "4", "name": "noi" }] },
{ "serialNo": "3", "text": "CCC", "subArray": [{ "id": "1", "name": "glo" }, { "id": "5", "name": "gum" }, { "id": "4", "name": "lom" }] }
];
Details = Details.map(function (data) {
if (data.serialNo === "1") {
data.subArray = data.subArray.filter(function (sa) {
return (sa.id !== "5");
});
}
return data;
});
console.log(Details);
The first problem is that you're not returning anything from the map functions. The second problem is that data.subArray[subDetails] is undefined, subDetails is an object not an index in the data.subArray array. You can use a combination of map and filter to accomplished this instead of using delete.
let Details = [
{ "serialNo": "1", "text": "AAA", "subArray": [{ "id": "1", "name": "geo" }, { "id": "5", "name": "gau" }, { "id": "4", "name": "joi" }] },
{ "serialNo": "2", "text": "BBB", "subArray": [{ "id": "7", "name": "rom" }, { "id": "5", "name": "dom" }, { "id": "4", "name": "noi" }] },
{ "serialNo": "3", "text": "CCC", "subArray": [{ "id": "1", "name": "glo" }, { "id": "5", "name": "gum" }, { "id": "4", "name": "lom" }] }
];
Details.map((data) => {
if (data.serialNo === "1") {
data.subArray = data.subArray.filter((subDetails) => {
return subDetails.id !== "5";
})
}
return data;
});
console.log(Details);
If you want to stick with map what you need to do is to return undefined when subDetails.id is 5.
let Details = [
{ "serialNo": "1", "text": "AAA", "subArray": [{ "id": "1", "name": "geo" }, { "id": "5", "name": "gau" }, { "id": "4", "name": "joi" }] },
{ "serialNo": "2", "text": "BBB", "subArray": [{ "id": "7", "name": "rom" }, { "id": "5", "name": "dom" }, { "id": "4", "name": "noi" }] },
{ "serialNo": "3", "text": "CCC", "subArray": [{ "id": "1", "name": "glo" }, { "id": "5", "name": "gum" }, { "id": "4", "name": "lom" }] }
];
Details.map((data) => {
if (data.serialNo === "1") {
data.subArray = data.subArray.filter((subDetails) => {
return subDetails.id === "5" ? undefined : subDetails;
})
}
return data;
});
console.log(Details);
One map plus object constructor:
const arr = [
{ "serialNo": "1", "text": "AAA", "subArray": [{ "id": "1", "name": "geo" }, { "id": "5", "name": "gau" }, { "id": "4", "name": "joi" }] },
{ "serialNo": "2", "text": "BBB", "subArray": [{ "id": "7", "name": "rom" }, { "id": "5", "name": "dom" }, { "id": "4", "name": "noi" }] },
{ "serialNo": "3", "text": "CCC", "subArray": [{ "id": "1", "name": "glo" }, { "id": "5", "name": "gum" }, { "id": "4", "name": "lom" }] }
];
const s = 1, id = 5; // conditions
const r = arr.map(e => (e.serialNo == s)
? Object.assign(e, {'subArray': e.subArray.filter(a => a.id != id)})
: e);
console.log(JSON.stringify(r, null, 2));
Object.assign swaps old subArray with the new filtered one.
I am using AngularJs doing a simple application And I want to set a variable up in a javascript file in orther to call a json file.
This is my data.js :
[{
var data = require('data_old.json');
var json = JSON.parse(data);
alert(json["date"]); //01/05/2016
alert(json.date); //01/05/2016
"name": "city A",
"elements": [{
"id": "c01",
"name": "name1",
"price": "15",
"qte": "10"
}, {
"id": "c02",
"name": "name2",
"price": "18",
"qte": "11"
}, {
"id": "c03",
"name": "name3",
"price": "11",
"qte": "14"
}],
"subsities": [{
"name": "sub A1",
"elements": [{
"id": "sub01",
"name": "nameSub1",
"price": "1",
"qte": "14"
}, {
"id": "sub02",
"name": "nameSub2",
"price": "8",
"qte": "13"
}, {
"id": "sub03",
"name": "nameSub3",
"price": "1",
"qte": "14"
}]
}, {
"name": "sub A2",
"elements": [{
"id": "ssub01",
"name": "nameSsub1",
"price": "1",
"qte": "7"
}, {
"id": "ssub02",
"name": "nameSsub2",
"price": "8",
"qte": "1"
}, {
"id": "ssub03",
"name": "nameSsub3",
"price": "4",
"qte": "19"
}]
}, {
"name": "sub A3",
"elements": [{
"id": "sssub01",
"name": "nameSssub1",
"price": "1",
"qte": "11"
}, {
"id": "sssub02",
"name": "nameSssub2",
"price": "2",
"qte": "15"
}, {
"id": "sssub03",
"name": "nameSssub3",
"price": "1",
"qte": "15"
}]
}]
}, {
"name": "city B",
"elements": [{
"id": "cc01",
"name": "name11",
"price": "10",
"qte": "11"
}, {
"id": "cc02",
"name": "name22",
"price": "14",
"qte": "19"
}, {
"id": "cc03",
"name": "name33",
"price": "11",
"qte": "18"
}]
}, {
"name": "city C",
"elements": [{
"id": "ccc01",
"name": "name111",
"price": "19",
"qte": "12"
}, {
"id": "ccc02",
"name": "name222",
"price": "18",
"qte": "17"
}, {
"id": "ccc03",
"name": "name333",
"price": "10",
"qte": "5"
}]
}]
And this is my data.json
[{
"date":"01/05/2016"
}]
I call my data here.
angular.module("myApp",['zingchart-angularjs'])
.controller('MainController', ['$scope', '$http', function($scope, $http) {
$scope.chartBase = {
"type": "line",
"plotarea": {
"adjust-layout": true /* For automatic margin adjustment. */
},
"scale-x": {
"label": {
"text": "Above is an example of a category scale" /* Add a scale title with a label object. */
},
"labels": ["name1", "name2", "name3"] /* Add your scale labels with a labels array. */
},
"series": [{
"values": [15, 18, 11] //here the prices of city selected
},{
"values": [10, 11, 14] //here the qte of city selected
}]
};
$scope.chartData = angular.copy($scope.chartBase);
$http.get('data.js')
.then(function(response) {
$scope.cities = response.data; // save the request data
$scope.selectedCity = $scope.cities[0]; // select the first one
$scope.changeCity(); // update chart
}, function(error) { console.log(error); });
$scope.changeCity = function() {
if($scope.selectedSubCity || $scope.selectedCity){ // if something has been selected
$scope.data = ($scope.selectedSubCity || $scope.selectedCity).elements; // update elements field
// initialize the array to be displayed in chart
var labels = [];
var price = {
"values": []
};
var qte = {
"values": []
};
// fill the arrays to be displayed from the selected city (sub city)
angular.forEach($scope.data, function(item, index) {
labels.push(item.name);
price.values.push(parseInt(item.price));
qte.values.push(parseInt(item.qte));
});
console.log($scope.chartData)
// put selected values to the field that is used to render the chart
$scope.chartData["scale-x"].labels = labels;
$scope.chartData.series = [ price, qte ];
}
}
}]);
When I run this, the browser tell that I have this error :
SyntaxError: Unexpected token v in JSON at position 5
at Object.parse (native)
You can't have those in your data.js file as they are not valid JSON
var data = require('data_old.json');
var json = JSON.parse(data);
alert(json["date"]); //01/05/2016
alert(json.date); //01/05/2016
The error is pointing to the first "v" of "var". You can test your JSON here http://json.parser.online.fr/ on some other online validator.
Your file should look like this:
[{
"name": "city A",
"elements": [{
"id": "c01",
"name": "name1",
"price": "15",
"qte": "10"
}, {
"id": "c02",
"name": "name2",
"price": "18",
"qte": "11"
}, {
"id": "c03",
"name": "name3",
"price": "11",
"qte": "14"
}],
"subsities": [{
"name": "sub A1",
"elements": [{
"id": "sub01",
"name": "nameSub1",
"price": "1",
"qte": "14"
}, {
"id": "sub02",
"name": "nameSub2",
"price": "8",
"qte": "13"
}, {
"id": "sub03",
"name": "nameSub3",
"price": "1",
"qte": "14"
}]
}, {
"name": "sub A2",
"elements": [{
"id": "ssub01",
"name": "nameSsub1",
"price": "1",
"qte": "7"
}, {
"id": "ssub02",
"name": "nameSsub2",
"price": "8",
"qte": "1"
}, {
"id": "ssub03",
"name": "nameSsub3",
"price": "4",
"qte": "19"
}]
}, {
"name": "sub A3",
"elements": [{
"id": "sssub01",
"name": "nameSssub1",
"price": "1",
"qte": "11"
}, {
"id": "sssub02",
"name": "nameSssub2",
"price": "2",
"qte": "15"
}, {
"id": "sssub03",
"name": "nameSssub3",
"price": "1",
"qte": "15"
}]
}]
}, {
"name": "city B",
"elements": [{
"id": "cc01",
"name": "name11",
"price": "10",
"qte": "11"
}, {
"id": "cc02",
"name": "name22",
"price": "14",
"qte": "19"
}, {
"id": "cc03",
"name": "name33",
"price": "11",
"qte": "18"
}]
}, {
"name": "city C",
"elements": [{
"id": "ccc01",
"name": "name111",
"price": "19",
"qte": "12"
}, {
"id": "ccc02",
"name": "name222",
"price": "18",
"qte": "17"
}, {
"id": "ccc03",
"name": "name333",
"price": "10",
"qte": "5"
}]
}]
var data = require('data_old.json');
var json = JSON.parse(data);
alert(json["date"]); //01/05/2016
alert(json.date); //01/05/2016
Why do you add those at the beginning of the JSON ? They cannot be parsed by your script, thus displaying the Syntax Error. What do you want to do exactly ?
I have object and I am trying to push data into it, but I am getting the error "push is not a function".
Here's my object:
var item = {
"_id": {
"$oid": "asdf976"
},
"Categories": [{
"mainmodels": [{
"submodels": [{
"price": "2000",
"submodelname": "lumia021",
"Remainingphones": "0",
"Bookedphones": "0",
"Numofphones": "10"
}, {
"price": "2000",
"submodelname": "lumia341",
"Remainingphones": "5",
"Bookedphones": "5",
"Numofphones": "10"
}
],
"Status": "Active",
"modelname": "lumia",
"fromdate": "2016-04-01T16:39:12.051Z",
"todate": "2016-04-31T19:19:44.051Z"
}],
"brand": "nokia"
}],
"rank": "1",
"name": "first"
}
I want to push:
var modal = {
'custid': '1',
'packcode': '22'
};
item.push(modal);
console.log(item);
Here's my expected result:
var item = {
"_id": {
"$oid": "asdf976"
},
"Categories": [{
"mainmodels": [{
"submodels": [{
"price": "2000",
"submodelname": "lumia021",
"Remainingphones": "0",
"Bookedphones": "0",
"Numofphones": "10"
}, {
"price": "2000",
"submodelname": "lumia341",
"Remainingphones": "5",
"Bookedphones": "5",
"Numofphones": "10"
}
],
"Status": "Active",
"modelname": "lumia",
"fromdate": "2016-04-01T16:39:12.051Z",
"todate": "2016-04-31T19:19:44.051Z"
}],
"brand": "nokia"
}],
"rank": "1",
"name": "first",
'custid': '1',
'packcode': '22'
};
How do I do that?
You don't push into objects, you push into arrays.
Based on what you've said you want, you do this:
item.custid = '1';
item.packcode = '22';
E.g., just assign properties to the object.
In ES2015, you could use Object.assign if having modal be separate is important:
var modal = {custid: '1', packcode: '22'};
Object.assign(item, modal);
...but I don't see a need for it here, and note that there's no ongoing link between modal and item.
Live Example:
var item = {
"_id": {
"$oid": "asdf976"
},
"Categories": [{
"mainmodels": [{
"submodels": [{
"price": "2000",
"submodelname": "lumia021",
"Remainingphones": "0",
"Bookedphones": "0",
"Numofphones": "10"
}, {
"price": "2000",
"submodelname": "lumia341",
"Remainingphones": "5",
"Bookedphones": "5",
"Numofphones": "10"
}
],
"Status": "Active",
"modelname": "lumia",
"fromdate": "2016-04-01T16:39:12.051Z",
"todate": "2016-04-31T19:19:44.051Z"
}],
"brand": "nokia"
}],
"rank": "1",
"name": "first"
};
item.custid = '1';
item.packcode = '22';
// Note: Just using JSON for *display*
document.body.innerHTML =
"<pre>" + JSON.stringify(item, null, 2) + "</pre>";
Or with Object.assign (requires an up-to-date browser or a shim):
var item = {
"_id": {
"$oid": "asdf976"
},
"Categories": [{
"mainmodels": [{
"submodels": [{
"price": "2000",
"submodelname": "lumia021",
"Remainingphones": "0",
"Bookedphones": "0",
"Numofphones": "10"
}, {
"price": "2000",
"submodelname": "lumia341",
"Remainingphones": "5",
"Bookedphones": "5",
"Numofphones": "10"
}
],
"Status": "Active",
"modelname": "lumia",
"fromdate": "2016-04-01T16:39:12.051Z",
"todate": "2016-04-31T19:19:44.051Z"
}],
"brand": "nokia"
}],
"rank": "1",
"name": "first"
};
var modal = {
custid: '1',
packcode: '22'
};
Object.assign(item, modal);
// Note: Just using JSON for *display*
document.body.innerHTML =
"<pre>" + JSON.stringify(item, null, 2) + "</pre>";
I know to work out simple concepts using backbone.js.below is my nested json file
{
"Re":
{
"Si":
[
{
"Def":
{
"StName": "Gau00",
"SID": "1",
"Parent": "",
"ParentID": "",
"Ty": "GAU",
"TypID": "2"
},
"Entities":
[
{
"EntityId": "2003",
"Index": "1",
"Value": "00"
},
{
"EntityId": "2006",
"Index": "1",
"Value": "B"
},
{
"EntityId": "2004",
"Index": "1",
"Value": "B"
},
{
"EntityId": "5",
"Index": "1",
"Value": "54"
},
{
"EntityId": "9007",
"Index": "1",
"Value": "1"
},
{
"EntityId": "9703",
"Index": "1",
"Value": "0"
}
],
"Connections":
[
{
"SourceID": "2",
"DestinationID": "1"
}
]
},
{
"Def":
{
"StName": "Tan",
"ID": "2",
"Parent": "",
"ParentID": "",
"Ty": "TA",
"TypID": "3"
},
"Entities": "",
"Connections":
[
{
"SourceElementID": "5",
"DestinationID": "2"
},
{
"SourceID": "2",
"DestinationID": "1"
}
]
}
]
}
}
Now with the StName i have to get all the other details from this nested json using backbone.js.Can anyone help me with ideas.
First convert JSON string to Javascript Object then use the following algorithm:
for each element in "Si":
if element["Def"]:
if element["Def"]["StName"] == "YOUR REQUIRED VALUE":
return element["Def"]
Write a function that takes your object, and iterate through the object and check StName with your required value. If condition true, return the current object.