I am trying to build an array of objects using the data I get from backend service using angularjs. Here is how I get the data
"mylist": [
{
"name": "Test1",
"moreInfo": {
"moreInfoText": "More test",
},
"companyInfo": {
"companyNameInfo": "ABC",
"url": "http://www.google.com",
}
},
{
"name": "Test2",
"moreInfo": {
"moreInfoText": "More test2",
},
"companyInfo": {
"companyNameInfo": "ABC2",
"url": "http://www.yahoo.com",
}
},
]
I want to parse it so I can combine it all in one array of objects like
[{"name": "Test1", "moreInfoText": "More test","companyNameInfo": "ABC", "url": "http://www.google.com"},{ "name": "Test2", "moreInfoText": "More test2","companyNameInfo": "ABC2", "url": ""}]
Try this:
var flatten = function(object) {
var newObj = {};
for (var key in object) {
var item = object[key];
if (typeof item !== 'object') {
newObj[key] = item;
}
else {
var flattened = flatten(item);
for (var k in flattened) {
newObj[k] = flattened[k];
}
}
}
return newObj;
};
var newList = [];
myList.forEach(function(object) {
newList.push(flatten(object);
});
console.log(newList) //this should be what you want
Related
I have an array list which needs to be converted to a single object with few of the values from array list using TypeScript in Angular 8. Below is the array:
"arrayList": [{
"name": "Testname1",
"value": "abc"
},
{
"name": "Testname2",
"value": "xyz"
}
]
This needs to be converted to the below format,
data: {
"Testname1": "abc",
"Testname2": "xyz",
}
No matter how much i try, i end up creating a list instead of a single object. Can you please help on the same?
You can use as follows,
var arr = [
{
"name": "Testname1",
"value": "abc"
},
{
"name": "Testname2",
"value": "xyz"
}
];
var result = {};
for (var i = 0; i < arr.length; i++) {
result[arr[i].name] = arr[i].value;
}
console.log(result);
Try with using .reduce() as the following:
const arrayList = [{ "name": "Testname1", "value": "abc" }, { "name": "Testname2", "value": "xyz" }];
const data = arrayList.reduce((a, {name, value}) => {
a[name] = value;
return a;
}, {});
const result = { data };
console.log(result);
Use Array.map() to get a list of [name, value] entries, then use Object.fromEntries() to convert to an object:
const arrayList = [{ "name": "Testname1", "value": "abc" }, { "name": "Testname2", "value": "xyz" }];
const result = Object.fromEntries(arrayList.map(({ name, value }) => [name, value]));
console.log(result);
Please use the below code
const rawData = {
"arrayList": [{
"name": "Testname1",
"value": "abc"
},
{
"name": "Testname2",
"value": "xyz"
}
]
};
const updatedData = {
data: {}
};
for (const item of rawData["arrayList"]) {
updatedData.data[item.name] = item.value;
}
console.log(updatedData);
Input:
{
"k1": "v1",
"k2": "v2",
"event": "SUMMARY"
}
Expected output:
{
"k1": "v1",
"k2": "v2",
"event": "SUMMARY",
"arr": [
{
"k1": "v1",
"key": "first"
},
{
"k2": "v2",
"key": "second"
},
{
"summary1": "s1",
"key": "SUMMARY"
},
{
"summary1": "s2",
"key": "SUMMARY"
}
]
}
For each 'k1' and 'k2', respective array element should be added as
{
"k2": "v2",
"key": "second"
}
For when event = "SUMMARY", respective 2 elements should be added as
{
"summary1": "s1",
"key": "SUMMARY"
},
{
"summary2": "s2",
"key": "SUMMARY"
}
Please help with JOLT specification
Since you gave input and output based on that i written
one function in javascript.
{
"k1": "v1",
"k2": "v2",
"event": "SUMMARY"
}
Well that function will work only for above input
and also you have to mention that whether u want output in which language...
//Input
var obj = {
"k1": "v1",
"k2": "v2",
"event": "SUMMARY"
}
//funciton calling
obj["arr"] = checkThis(obj);
//output
console.log(obj)
function checkThis(obj) {
var arr = [];
Object.keys(obj)
.forEach(function eachKey(key) {
if (key == "k1") {
var tempObj = {}
tempObj["k1"] = obj[key];
tempObj["key"] = "first";
arr.push(tempObj)
} else if (key == "k2") {
var tempObj = {}
tempObj["k2"] = obj[key];
tempObj["key"] = "second";
arr.push(tempObj)
} else if (key == "event") {
var tempObj1 = {}
var tempObj2 = {}
tempObj1["summary1"] = "s1";
tempObj1["key"] = obj[key];
tempObj2["summary1"] = "s2";
tempObj2["key"] = obj[key];
arr.push(tempObj1)
arr.push(tempObj2)
}
});
return arr;
}
Hi i have excel upload functionality when i upload the excel that should save in to the mongodb(database). I have taken the excel cell value as json stringify and also i converted that as parse. now i don't how to get that json length value.
here i have attached my code
function to_json(workbook) {
debugger;
console.log(workbook);
var result = {};
workbook.SheetNames.forEach(function(sheetName) {
$scope.Sheetname=sheetName; // here sheet name is excel sheet name
MainSheetName=sheetName;
var roa = X.utils.sheet_to_json(workbook.Sheets[sheetName]);
if(roa.length > 0){
result[sheetName] = roa;
}
});
return result;
}
var HTMLOUT = document.getElementById('htmlout');
function to_html(workbook) {
HTMLOUT.innerHTML = "";
workbook.SheetNames.forEach(function(sheetName) {
var htmlstr = X.write(workbook, {sheet:sheetName, type:'binary', bookType:'html'});
HTMLOUT.innerHTML += htmlstr;
});
}
var tarea = document.getElementById('b64data');
function b64it() {
if(typeof console !== 'undefined') console.log("onload", new Date());
var wb = X.read(tarea.value, {type: 'base64',WTF:wtf_mode});
process_wb(wb);
}
window.b64it = b64it;
var OUT = document.getElementById('out');
var global_wb;
function process_wb(wb) {
global_wb = wb;
var output = "";
var output1 = "";
switch(get_radio_value("format")) {
case "json":
output = JSON.stringify(to_json(wb), 2, 2);
output1=JSON.parse(output);
break;
case "form":
output = to_formulae(wb);
break;
case "html": return to_html(wb);
default:
output = to_csv(wb);
}
if(OUT.innerText === undefined) OUT.textContent = output;
else OUT.innerText = output;
debugger;
$scope.MainInfo=output1; // this return whole data
console.log(output1);
$scope.jsondata=output1.Sheet1[0].length;// this returns undefined. Here sheet name is excel file sheetName it will taken from excel.
console.log($scope.jsondata);
my output is showing like this
{
"Sheet1": [
{
"Name": "xxx",
"Age": "22",
"Salary": "222222"
},
{
"Name": "yyy",
"Age": "23",
"Salary": "232323"
},
{
"Name": "zzz",
"Age": "23",
"Salary": "232323"
}
]
}
now i want length of Sheet1 how can i get that. can any one tell me
If you were to assign your output to obj getting the length of Sheet1 would be as simple as going obj.Sheet1.length
Try this :
var output = {
"Sheet1": [{
"Name": "xxx",
"Age": "22",
"Salary": "222222"
}, {
"Name": "yyy",
"Age": "23",
"Salary": "232323"
}, {
"Name": "zzz",
"Age": "23",
"Salary": "232323"
}]
};
var newArr = $.grep(output1.Sheet1, function( value, index ) {
if(n.Name == "xxx") {
return n;
}
});
console.log(newArr)
You can use angular.fromJson(yourJson).length functionality.
In your case, it should be angular.fromJson($scope.jsondata).length.
As per my understanding from above code, your are getting response into JSON string format so you can't perform JSON operation over it. try to convert json string to json object using JSON.parse method.Below is sample code in node js.
var parseData = JSON.parse(output1);
var parsedata1 = parseData.Sheet1;
for(var namevalue=0;namevalue<parsedata.length;namevalue++){
console.log("Name value: "+parsedata1[namevalue].Name);
}
I want to push an item to the array of items (root document > categories > subcategories > items)
I am using NodeJS with MongoDB npm package
My document structure should be like the following
{
"_id": "572a77641b24ed3404f43690"
"categories": [
{
"id": "572bbac072d7ee3026a69467"
"Name": "Foods",
"subcategories": [
{
"id": "572a777c1b24ed3404f43691",
"Name": "Pizza"
"items": [
{
"id": "572ba1666ca263303121acd4"
"Name": "4 Seasons",
"Price": "6.0"
}
]
}
]
}
]
}
My current code is
app.post("/item/:subcatid", function(req, res) {
var subId = req.params.subcatid;
var item = req.body;
item.id = new ObjectId();
items.update({ "categories.subcategories.id": ObjectId(subId) }, { $push: { "categories.0.subcategories.$.items": item } }, function(err, result) {
res.send(result);
});
});
What can I do ?
Just found a solution, not clean one though but works properly !
app.post("/item/:subcatid", function(req, res) {
var subId = req.params.subcatid;
var item = req.body;
item.id = new ObjectId();
items.findOne({ "categories.subcategories.id": ObjectId(subId) }, { "categories.subcategories.$": 1 }, function(err, doc) {
for (var i = 0; i < doc.categories[0].subcategories.length; i++) {
var elem = doc.categories[0].subcategories[i];
if (elem.id == subId) {
items.update({ "categories.subcategories.id": ObjectId(subId) }, { $push: { ["categories." + i + ".subcategories.$.items"]: item } }, function(err, result) {
res.send(result);
});
break;
}
}
});
});
How I can create a $filter with custom function to determining if match ?
This is a json sample with structure:
$scope.routes =[
{
"id": 0,
"name": "Rosa Barnes",
"origin": [
{
"address": [
{
"locality": "Madrid",
"country": "ES"
}
]
}
]
},
{
"id": 1,
"name": "Wright Montoya",
"origin": [
{
"address": [
{
"locality": "London",
"country": "UK"
}
]
}
]
},
{
"id": 2,
"name": "Pearson Johns",
"origin": [
{
"address": [
{
"locality": "London",
"country": "UK"
}
]
}
]
}
];
I want a $filter that passing one country, match in origin.address.country , is possible?
I proved this code but not works:
$scope.routesToShow = $filter('filter')($scope.routes, {origin.address.country: "UK"});
Here there are a demo:
http://jsfiddle.net/86U29/43/
Thanks
What you need is a custom filter. It also looks like you might need to tweak your data structure too.
Take a look at this:
app.filter('CustomFilter', function () {
function parseString(propertyString) {
return propertyString.split(".");
}
function getValue(element, propertyArray) {
var value = element;
propertyArray.forEach(function (property) {
value = value[property];
});
return value;
}
return function (input, propertyString, target) {
var properties = parseString(propertyString);
return input.filter(function (item) {
return getValue(item, properties) == target;
});
}
});
You could use this filter, like this:
$scope.routesToShow = $filter('CustomFilter')($scope.routes, 'origin.address.country', 'UK');
Here is an updated jsfiddle (notice the updated data structure): http://jsfiddle.net/moderndegree/86U29/44/
You can find more information on creating custom filters here:
https://docs.angularjs.org/guide/filter#creating-custom-filters
Simply.
var filter = function(obj){
return obj.origin[0].address[0].country === 'UK';
}
$scope.routesToShow = $filter('filter')($scope.routes, filter);