dynamic create json for treeview - json

I want to turn json
var treeNodes = [ {managerid:root,Employeeid:01},
{managerid:01,Employeeid:11},
{managerid:01,Employeeid:22},
{managerid:22,Employeeid:33},
{managerid:22,Employeeid:44}
];
into json like this using javascript.
json={
id:root,
children[{
id:01,
children[
{id:11},
{id:22}
]
children[
{id:33},
{id:44}
]
}
Can someone help with java script function?

First of all, your current JSON is incorrect:
var json = {
id: root,
children: [
{
id: 01,
children: [
{id: 11},
{id: 22}
]
},
{
children: [
{id: 33},
{id: 44}
]
}
]
};
Second, could you give more information about your table Employee?

Related

How to transpose array of objects in TypeScript?

I am having an array of objects as below:
finalList = [
[{name: john}, {name: max}, {name: rob}],
[{id: 1}, {id: 2}, {id: 3}],
[{gender: M}, {gender: F}, {gender: M}],
]
I need the array to transpose like this:
finalList = [
{name: john, id: 1, gender: M},
{name: john, id: 1, gender: M},
{name: john, id: 1, gender: M}
]
The actual array of object is in nested array. Please help me guiding to transpose the array in TypeScript.
Here's a nice functional way. It assumes each array in finalList has the same length and same keys (so no error handling).
const finalList = [
[{name: "john"}, {name: "max"}, {name: "rob"}],
[{id: 1}, {id: 2}, {id: 3}],
[{gender: "M"}, {gender: "F"}, {gender: "M"}],
];
console.log(finalList);
// this is a trick to create an array of a specific size with unique objects inside it
// the fill is necessary to iterate over the holed array (https://stackoverflow.com/q/40297442/2178159)
// fill({}) won't work since it's a single object ref that will be shared
const results = new Array(finalList.length).fill(null).map(() => ({}));
finalList.forEach(group => {
group.forEach((obj, i) => {
Object.assign(results[i], obj);
})
});
console.log(results);

Deleting deep in an array with immutablejs

I am trying to perform a complex deletion in Immutablejs, without, what I always seem to do, converting to JS in the middle of the process.
In the following array, I would like to delete every second {y: } object
series: [
{
name:"1",
data: [
{y: 1},
{y: 2},
{y: 3}
]
},
{
name:"2",
data: [
{y: 1},
{y: 2},
{y: 3}
]
},
{
name:"3",
data: [
{y: 1},
{y: 2},
{y: 3}
]
}
]
So that I would get this :
series: [
{
name:"1",
data: [
{y: 1},
{y: 3}
]
},
{
name:"2",
data: [
{y: 1},
{y: 3}
]
},
{
name:"3",
data: [
{y: 1},
{y: 3}
]
}
]
Can someone point me in the correct direction how to do this with ImmutableJS? If I just use filter or array reduce I can arrive at a really clean solution that looks like this :
series.forEach(function (elem) {
let data = elem.data;
data.splice(index, 1);
});
I am just hoping that immutable has an equally clean looking solution.
The doc for removeIn doesn't go deep enough :
https://facebook.github.io/immutable-js/docs/#/removeIn
You're modifying every element of series so I think you're on the right track with .map(). Then you want to use .removeIn to deeply remove something.
let seriesList = Immutable.fromJS(series)
seriesList = seriesList.map(elem =>
elem.removeIn(['data', indexToRemove]));
// equivalent form with .update() instead of .removeIn()
seriesList = seriesList.map(elem =>
elem.update('data', data => data.remove(indexToRemove)));
I managed to do it using 'map' from Immutable List. This worked for me :
seriesList = Immutable.List(seriesList);
seriesList = seriesList.map(
elem => {
let data = elem.getIn(['data'])
data = data.remove(index)
elem = elem.setIn(['data'], data)
return elem
})
Anyone have something better?

Extract child objects from json object

I am struggling to convert xml to json object and then extracting nodes from the converted object. I am using busyboy to read from the file uploaded on the server. And after that I am using inspect to convert xml to json and then printing the json object. The final output seems as
{ declaration: { attributes: { version: '1.0', encoding: 'utf-8' } },
root:
{ name: 'order',
attributes:
{ orderid: '123456',
xmlns: 'http://www.someRandomNameSpace.com' },
children:
[ { name: 'orderperson',
attributes: {},
children: [],
content: 'str1234' },
{ name: 'shipto',
attributes: {},
children:
[ { name: 'name',
attributes: {},
children: [],
content: 'Adnan Ali' },
I want to read the 'name'='Adnan Ali' from this object how will that be done in nodejs ? I mean how can i reach to the object which has name='name' and content='Adnan Ali'.
The print command is
console.log(inspect(order, {colors: true, depth: Infinity}));
Since you are using NodeJS perhaps giving JSONPath a try would be a good idea. Then you can do something like this:
var jp = require("JSONPath");
var tobj = { "declaration": { "attributes": { "version": '1.0', "encoding": 'utf-8' } },
"root":
{ "name": 'order',
"attributes":
{ "orderid": '123456',
"xmlns": 'http://www.someRandomNameSpace.com' },
"children":
[ { "name": 'orderperson',
"attributes": {},
"children": [],
"content": 'str1234' },
{ "name": 'shipto',
"attributes": {},
"children":
[ { "name": 'name',
"attributes": {},
"children": [],
"content": 'Adnan Ali'
}
]
}
]
}};
var result = jp.eval(tobj, "$..children[?(#.name === 'name' && #.content === 'Adnan Ali')]");
console.log(result);
Example output:
[ { name: 'name',
attributes: {},
children: [],
content: 'Adnan Ali' } ]
(Don't forget to install JSONPath ;-))
Sources:
https://www.npmjs.com/package/JSONPath
http://goessner.net/articles/JsonPath/
You need to search the arrays of objects for the objects you are interested in. There are various ways to do that, including Array.prototype.find (not sure if it is available in all Node.js versions) and lodash _.find.
Using Array.prototype.filter a solution could look like this (not tested):
function findObject(array, key, value) {
var filtered = array.filter(obj => (obj[key] === value));
if (filtered.length !== 1) throw new Error('Found ' + filtered.length + ' objects with `' + key + '`=`' + value + '`, expected to find 1.');
return filtered[0];
}
var shipto = findObject(input.root.children, 'name', 'shipto');
var name = findObject(shipto.children, 'name', 'name').content;
console.log(name);
You should be able to reach the object with content: 'Adnan Ali' with this path data.root.children[1].children[0]:
const data = {
declaration: {
attributes: {
version: '1.0',
encoding: 'utf-8'
}
},
root: {
name: 'order',
attributes: {
orderid: '123456',
xmlns: 'http://www.someRandomNameSpace.com'
},
children: [{
name: 'orderperson',
attributes: {},
children: [],
content: 'str1234'
}, {
name: 'shipto',
attributes: {},
children: [{
name: 'name',
attributes: {},
children: [],
content: 'Adnan Ali'
}]
}]
}
};
console.log(data.root.children[1].children[0])
Explanation:
data is an object that contains a root object. root is an object that contains a children array. The second element in root.children (index 1) is an object that contains another children array that contains the object you're looking for at the first index (0).
Consider using object-scan. It's very powerful once you wrap your head around it.
// const objectScan = require('object-scan');
const find = (input) => objectScan(['**'], {
abort: true,
rtn: 'value',
filterFn: ({ value }) => value.content === 'Adnan Ali' && value.name === 'name'
})(input);
const tobj = { declaration: { attributes: { version: '1.0', encoding: 'utf-8' } }, root: { name: 'order', attributes: { orderid: '123456', xmlns: 'http://www.someRandomNameSpace.com' }, children: [{ name: 'orderperson', attributes: {}, children: [], content: 'str1234' }, { name: 'shipto', attributes: {}, children: [{ name: 'name', attributes: {}, children: [], content: 'Adnan Ali' }] }] } };
console.log(find(tobj));
// => { name: 'name', attributes: {}, children: [], content: 'Adnan Ali' }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan

Get Array Of Object On ajax Call success

I will make Ajax call on my Controller action method. I want result of JSON in this format.
// array of all brands
var brands = [
{ brandId: 1, name: "Ford" },
{ brandId: 2, name: "BMW" }
];
for this i will make another call
// array of all models
var models = [
{ modelId: 1, name: "Explorer", brandId: 1},
{ modelId: 2, name: "Focus", brandId: 1},
{ modelId: 3, name: "X3", brandId: 2},
{ modelId: 4, name: "X5", brandId: 2}
];
How can i do that please guide me.
You can use following code to solve your problem
public ActionResult SomeActionMethod(int id)
{
return Json(new {foo="bar", baz="Blech"});
}
Method from the jquery getJSON method by simply...
$.getJSON("../SomeActionMethod", { id: someId },
function(data) {
alert(data.foo);
alert(data.baz);
}
);
To serialize json in your controller, may be you can use http://www.newtonsoft.com/json/help/html/serializingjson.htm

ImmutableJS: Convert List to indexed Map

This question is about Immutable.js library.
I have a List<T>, where T is {name: string, id: number}. I want to convert it to Map<number, T>, with id of T to the keys. Using standard method toMap gives me a Map with sequential indexes, and there is no way to hook there. And no method like indexBy or other. how to do that?
You can do it with a reducer like this:
function indexBy(iterable, searchKey) {
return iterable.reduce(
(lookup, item) => lookup.set(item.get(searchKey), item),
Immutable.Map()
);
}
var things = Immutable.fromJS([
{id: 'id-1', lol: 'abc'},
{id: 'id-2', lol: 'def'},
{id: 'id-3', lol: 'jkl'}
]);
var thingsLookup = indexBy(things, 'id');
thingsLookup.toJS() === {
"id-1": { "id": "id-1", "lol": "abc" },
"id-2": { "id": "id-2", "lol": "def" },
"id-3": { "id": "id-3", "lol": "jkl" }
};