get array of parent and all of its child - javascript

suppose I have this kind of data...
data = [{
"_id" : "1",
"parentId" : "thisPostId",
"topLevelId" : "1",
"text" : "<p>comment</p>",
},
{
"_id" : "2",
"parentId" : "1",
"topLevelId" : "1",
"text" : "<p>reply to comment</p>",
},
{
"_id" : "3",
"parentId" : "2",
"topLevelId" : "1",
"text" : "<p>reply to reply to comment</p>",
},
{
"_id" : "4",
"parentId" : "3",
"topLevelId" : "1",
"text" : "<p>reply to reply to reply to comment</p>",
}]
I need to remove a comment and all of its child...
if comment to remove is _id:1,, then I need an array of ["1","2","3","4"],,, then i can run Coll.remove({_id:{$in:["1","2","3","4"]}}, callback);
if comment to remove is _id:2,, then I need an array of ["2","3","4"]
if comment to remove is _id:3,, then I need an array of ["3","4"]
if comment to remove is _id:4,, then I need an array of ["4"]
I tried this (with no idea)...
_.forEach(data, function(value, key){
_.pluck(_.where(key, { "parentId" : "2" }), '_id');
});
and not working...
any help with javascript/lodash/underscore will be appreciated,,,
thank You...

Here is another interpretation using the native Array.prototype.reduce method to only add the child elements to the returned array.
edit, didn't read question properly, this will now return the current id and all children.
var data = [{
"_id" : "1",
"parentId" : "thisPostId",
"topLevelId" : "1",
"text" : "<p>comment</p>",
},
{
"_id" : "2",
"parentId" : "1",
"topLevelId" : "1",
"text" : "<p>reply to comment</p>",
},
{
"_id" : "3",
"parentId" : "2",
"topLevelId" : "1",
"text" : "<p>reply to reply to comment</p>",
},
{
"_id" : "4",
"parentId" : "3",
"topLevelId" : "1",
"text" : "<p>reply to reply to reply to comment</p>",
}];
function getChildIds( arr, id ){
var parentFound = false;
return arr.reduce(function( ret, item ){
if( parentFound === false && item._id == id ){
parentFound = true;
}
if( parentFound ) {
ret = ret.concat( item._id );
}
return ret;
}, []);
}
console.log( getChildIds(data, '1') );
console.log( getChildIds(data, '2') );
console.log( getChildIds(data, '3') );
console.log( getChildIds(data, '4') );
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
any order, not sure why it's necessary thought.
var data = [{
"_id": "2",
"parentId": "1",
"topLevelId": "1",
"text": "<p>reply to comment</p>",
}, {
"_id": "1",
"parentId": "thisPostId",
"topLevelId": "1",
"text": "<p>comment</p>",
}, {
"_id": "4",
"parentId": "3",
"topLevelId": "1",
"text": "<p>reply to reply to reply to comment</p>",
}, {
"_id": "3",
"parentId": "2",
"topLevelId": "1",
"text": "<p>reply to reply to comment</p>",
}];
function getChildIdsInAnyOrder(arr, id) {
return arr.reduce(function(ret, item) {
if ( parseInt(item._id) >= parseInt(id) ) {
ret = ret.concat(item._id);
}
return ret;
}, []);
}
console.log(getChildIdsInAnyOrder(data, '1'));
console.log(getChildIdsInAnyOrder(data, '2'));
console.log(getChildIdsInAnyOrder(data, '3'));
console.log(getChildIdsInAnyOrder(data, '4'));
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

This is a rather lengthy one using recursion,
function getIDs(arr, id) {
arr = arr || data;
var ret = [];
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
if (item.parentId == id || item._id == id) {
if (ret.indexOf(item._id) < 0) {
ret.push(item._id);
var newret = []
for (var x = 0; x < arr.length; x++) {
if (x != i) newret.push(arr[x]);
}
var children = getIDs(newret, item._id);
if (children.length > 0) {
for (var j = 0; j < children.length; j++) {
if (!(ret.indexOf(children[j]) >= 0)) { ret.push(children[j]); }
}
}
}
}
}
return ret;
}
It works by getting the id of the desired parent, then getting the ids of its children, and its children's children, it could do this all day ...

First you need a function to get the topLevelId from the object with that matches the search id:
function getTLID(searchId) {
return data.filter(function(el) {
return el._id === searchId;
})[0].topLevelId;
}
With reduce: add the _id of each object to the returned array that has that search id and either have the search id or have a parentId greater or equal to the search id, the use map to grab the _ids.
function getIdArray(searchId) {
var tlid = getTLID(searchId);
return data.reduce(function (p, c) {
var matchSearchId = +c.parentId >= +searchId || c._id === searchId;
if (c.topLevelId === tlid && matchSearchId) p.push(c._id);
return p;
}, []).sort();
}
getIdArray('1') // [ "1", "2", "3", "4" ]
getIdArray('2') // [ "2", "3", "4" ]
getIdArray('3') // [ "3", "4" ]
getIdArray('4') // [ "4" ]
DEMO
If you don't like reduce, perhaps using filter and map.
function getIdArray(searchId) {
var tlid = getTLID(searchId);
return data.filter(function(el) {
var matchSearchId = +el.parentId >= +searchId || el._id === searchId;
return el.topLevelId === tlid && matchSearchId;
}).map(function(el) {
return el._id;
}).sort();
}
DEMO

This is a proposal with a temporary object and a recursive call for the ids.
The temporary object o contains all ids and their childrens
{
"1": ["2"],
"2": ["3"],
"3": ["4"],
"thisPostId": ["1"]
}
After this object is build, the id for the look up is taken and checked if the object contains the property. While all peopertys are arrays, it is possible to iterate over go() and get all id for collecting. If there is another child, the recursive iteration is going on.
var data = [{ "_id": "1", "parentId": "thisPostId", "topLevelId": "1", "text": "<p>comment</p>", }, { "_id": "2", "parentId": "1", "topLevelId": "1", "text": "<p>reply to comment</p>", }, { "_id": "3", "parentId": "2", "topLevelId": "1", "text": "<p>reply to reply to comment</p>", }, { "_id": "4", "parentId": "3", "topLevelId": "1", "text": "<p>reply to reply to reply to comment</p>", }];
function getConnected(s) {
function go(a) { r.push(a); o[a] && o[a].forEach(go); }
var o = data.reduce(function (r, a) {
r[a.parentId] = r[a.parentId] || [];
r[a.parentId].push(a._id);
return r;
}, {}),
r = [s];
o[s] && o[s].forEach(go);
return r;
}
for (var i = 1; i <= 4; i++) {
document.write('"' + i + '": ' + JSON.stringify(getConnected(i.toString())) + '<br>');
}

TRY THIS:
HTML:
<input type="text" id="Txt" />
<button type="button" onclick="check();">
Check
</button>
JS:
data = [{
"_id" : "1",
"parentId" : "thisPostId",
"topLevelId" : "1",
"text" : "<p>comment</p>",
},
{
"_id" : "2",
"parentId" : "1",
"topLevelId" : "1",
"text" : "<p>reply to comment</p>",
},
{
"_id" : "3",
"parentId" : "2",
"topLevelId" : "1",
"text" : "<p>reply to reply to comment</p>",
},
{
"_id" : "4",
"parentId" : "3",
"topLevelId" : "1",
"text" : "<p>reply to reply to reply to comment</p>",
}];
function check() {
getIds(document.getElementById("Txt").value);
}
function getIds(id) {
var allow = false,
result = [];
for (var i = 0; i < data.length; i++) {
if (data[i]._id == id) {
allow = true;
}
if (allow) {
result.push(data[i]._id)
}
}
retrun result;
}

You can try something like this:
Code
JSFiddle
var data = [{
"_id": "1",
"parentId": "thisPostId",
"topLevelId": "1",
"text": "<p>comment</p>",
}, {
"_id": "2",
"parentId": "1",
"topLevelId": "1",
"text": "<p>reply to comment</p>",
}, {
"_id": "3",
"parentId": "2",
"topLevelId": "1",
"text": "<p>reply to reply to comment</p>",
}, {
"_id": "4",
"parentId": "3",
"topLevelId": "1",
"text": "<p>reply to reply to reply to comment</p>",
}];
function getDependentList(id) {
var retList = [];
data.forEach(function(item) {
if (item.parentId == id)
retList.push(item["_id"]);
});
if (retList.length > 0) {
retList.forEach(function(item) {
retList = retList.concat(getDependentList(item).slice(0));
});
}
return retList;
}
function getRemoveList() {
var id = document.getElementById("txtInput").value;
var removeList = [];
removeList.push(id);
removeList = removeList.concat(getDependentList(id))
console.log(removeList);
}
<input type="text" id="txtInput">
<button onclick="getRemoveList()">get Lists</button>

First of all, you need to get the index of the item having mentioned _id, If item exists in the array then you can use array.splice to remove the n elements from mentioned index. To get items from the deleted node, deepcopy of the array is stored in temperory variable.
The splice() method changes the content of an array by removing existing elements and/or adding new elements.
You can calculate the delete count using data.length - index
var data = [{
"_id": "1",
"parentId": "thisPostId",
"topLevelId": "1",
"text": "<p>comment</p>",
}, {
"_id": "2",
"parentId": "1",
"topLevelId": "1",
"text": "<p>reply to comment</p>",
}, {
"_id": "3",
"parentId": "2",
"topLevelId": "1",
"text": "<p>reply to reply to comment</p>",
}, {
"_id": "4",
"parentId": "3",
"topLevelId": "1",
"text": "<p>reply to reply to reply to comment</p>",
}];
var getIndex = function(_id) {
for (var i = 0; i < data.length; i++) {
if (data[i]._id == _id) {
return i;
}
}
};
function deepCopy(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
var _id = 1;
var index = getIndex(_id);
var _temp = deepCopy(data);
var removedData = data.splice(index, 1);
alert(removedData);
if (typeof index !== 'undefined') {
var neededData = _temp.splice(index, (_temp.length - index));
alert(neededData);
}
Fiddle here

In the OP's comments, you said you're using meteorjs and you seem to want to cascade delete a document. Meteorjs hooks allow this easily:
var idToRemove;
Coll.remove({ _id: idToRemove }, callback);
// what to do after removing a Coll document
Coll.after.remove(function (userId, doc) {
Coll.remove({ parentId: doc._id });
});
You need to install the collection-hooks package first.

Related

sort JSON data and get top n records

I have a json data of around millions of records. I have to do a simple but tricky functionality.
What I have to do?
I have to gather top 10 most appeared item from that json with it's count. by most appeared, I mean the most count of the item in json. I am not sure yet, how I will go with count, I mean I can add it to same json obejct as property.
Here is what I did so far.
//my origional json, it's too big but adding some portion of it.
var jsonData = [
{
"id": "5",
"name": "#5"
},
{
"id": "1",
"name": "#1"
},
{
"id": "2",
"name": "#2"
},
{
"id": "8",
"name": "#8"
},
{
"id": "1",
"name": "#1"
},
{
"id": "10",
"name": "#10"
},
{
"id": "2",
"name": "#2"
}];
var top10Data = [];
//geting top 10 items
function getTop10Data() {
var i = 0;
while (i <= 20) {
top10Data.push(getTop1Data());
i++;
}
return true;
}
//getting top 1 data that has max count in json
function getTop1Data() {
var store = jsonData, distribution = {}, max = 0, result = [];
store.forEach(function (a) {
distribution[a] = (distribution[a] || 0) + 1;
if (distribution[a] > max) {
max = distribution[a];
result = [a];
return;
}
if (distribution[a] === max) {
result.push(a);
}
});
//remove this item with it's all occurences, and push it to top10Data
removeData(result);
return result;
}
//remove items from origional json. but this is not working properly as it removes only one item from top
function removeData(result) {
var length = jsonData.length;
for (var i = 0; i < length; i++) {
if (jsonData[i].toppings === result[0].toppings) {
jsonData.splice(jsonData[i], 1);
}
}
}
My question.
I think the way I am going is not proper, is there any better approach to handle this situation. and if mine approach is ok, what I am missing in current code.
any help would be really appreciated.
You could reduce the data into an object that holds the count of each item, indexed by the stringified item. Then, if there aren't an reasonably huge number of unique objects, you can sort the entries by their number of occurrences, and then slice the first 10.
var jsonData = [
{
"id": "5",
"name": "#5"
},
{
"id": "1",
"name": "#1"
},
{
"id": "2",
"name": "#2"
},
{
"id": "8",
"name": "#8"
},
{
"id": "1",
"name": "#1"
},
{
"id": "10",
"name": "#10"
},
{
"id": "2",
"name": "#2"
}];
const counts = jsonData.reduce((a, obj) => {
const string = JSON.stringify(obj);
a[string] = (a[string] || 0) + 1
return a;
}, {});
const result = Object.entries(counts)
.sort((a, b) => b[1] - a[1])
.slice(0, 10)
.map(([string, count]) => ({ count, obj: JSON.parse(string) }));
console.log(result);
To add the counts to the original data, iterate over the data once the counts object is constructed:
var jsonData = [
{
"id": "5",
"name": "#5"
},
{
"id": "1",
"name": "#1"
},
{
"id": "2",
"name": "#2"
},
{
"id": "8",
"name": "#8"
},
{
"id": "1",
"name": "#1"
},
{
"id": "10",
"name": "#10"
},
{
"id": "2",
"name": "#2"
}];
const counts = jsonData.reduce((a, obj) => {
const string = JSON.stringify(obj);
a[string] = (a[string] || 0) + 1
return a;
}, {});
jsonData.forEach((item) => {
item.count = counts[JSON.stringify(item)];
});
console.log(jsonData);
I created one logic and it is working.
The steps are as follows :
Sort the array based on the name
Read the sorted array and count the number of name appearing
continuously and store the count number
Sort again based on the number of count
Sample code is attached. Please take a look at the final result.
var jsonData = [
{
"id": "5",
"name": "#5"
},
{
"id": "1",
"name": "#1"
},
{
"id": "2",
"name": "#2"
},
{
"id": "8",
"name": "#8"
},
{
"id": "1",
"name": "#1"
},
{
"id": "10",
"name": "#10"
},
{
"id": "2",
"name": "#2"
}];
$('#output1').html(JSON.stringify(jsonData));
jsonData.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
$('#output2').html(JSON.stringify(jsonData));
let newArray= [];
let total = 1;
for(let i=0;i<jsonData.length;i++){
let nextName = (i==jsonData.length -1)?0 : jsonData[i+1].name;
let currentName = jsonData[i].name;
if(nextName != currentName){
newArray.push({
id : jsonData[i].id,
name : currentName,
count : total
});
total = 1;
}
else{
total+=1;
}
}
$('#output3').html(JSON.stringify(newArray));
//Lets sort it again based on count and take the top 10
newArray.sort((a, b) => a.count > b.count ? -1 : a.count < b.count ? 1 : 0)
newArray = newArray.slice(0, 10); // Here is your Data
$('#output4').html(JSON.stringify(newArray));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="output1">
</p>
<p id="output2">
</p>
<p id="output3">
</p>
<p id="output4">
</p>

React : Filter or map Object by iterating through list of objects

I have list of CutomerType objects and Customer object. Customer object has the cutomerType id property on it. Based on the customer type id on customer object I have to loop over or map the right customerType object and disaplay the name code.
[ {
"id" : "5436d5fd-e3ea-4e09-be4a-a80967cd72e5",
"code" : "0",
"name" : "UN"
}, {
"id" : "674b76b8-f1ac-5c14-e053-ce5e1cac867d",
"code" : "1",
"name" : "NON-UN"
}, {
"id" : "674b76b8-f1ad-5c14-e053-ce5e1cac867d",
"code" : "2",
"name" : "COS-UN"
}, {
"id" : "674b76b8-f1ae-5c14-e053-ce5e1cac867d",
"code" : "NA",
"name" : NA"
} ]
Customer
{
"id" : "1",
"name": "Jhon",
"type": "5436d5fd-e3ea-4e09-be4a-a80967cd72e5",
}
This is what you could do.
const customerCodeArray = [{
"id": "5436d5fd-e3ea-4e09-be4a-a80967cd72e5",
"code": "0",
"name": "UN"
}, {
"id": "674b76b8-f1ac-5c14-e053-ce5e1cac867d",
"code": "1",
"name": "NON-UN"
}, {
"id": "674b76b8-f1ad-5c14-e053-ce5e1cac867d",
"code": "2",
"name": "COS-UN"
}, {
"id": "674b76b8-f1ae-5c14-e053-ce5e1cac867d",
"code": "NA",
"name": "NA"
}]
const customer = {
"id": "1",
"name": "Jhon",
"type": "5436d5fd-e3ea-4e09-be4a-a80967cd72e5",
};
const getCustomerCode = (type) => {
const filterList = customerCodeArray.filter((obj) => obj.id === type);
if (filterList.length > 0) {
return filterList[0];
}
}
console.log(getCustomerCode(customer.type));
Hope this is clear, if not feel free to ask
const loop = // whole array;
const customer = // customer object
loop.find(el => el.id === customer.type).name
const filteredResult = customerCodeArray.filter(type => type.id === Customer.type);
console.log(filteredResult[0].name);

custom jstree JSON data parse into tree

i have a simple JSON data which is this :
[
"env/child1/env/key1",
"env/child1/key1",
"env/child1/key2",
"env/child1/",
"env/child2/key1",
"env/child2/key2",
"env/child2/",
"env/"
]
how can i make jsTree understands this tree and draw the tree ?
env
child1
key1
key2
do i need to write a custom parsing function or is there a ready way for that.
tree = {
'core' : {
'data' : [
]
}
}
data = [
"env/child1/env/key1",
"env/child1/key1",
"env/child1/key2",
"env/child1/",
"env/child2/key1",
"env/child2/key2",
"env/child2/",
"env/"
];
minlen = -1;
picked = "";
for(i =0; i<data.length; i++) {
if(data[i].length < minlen || minlen == -1) {
minlen = data[i].length;
picked = data[i];
}
}
tree.core.data.push({ "id" : picked, "parent" : "#", "text" : picked })
xdata = data
xdata.splice(xdata.indexOf(picked), 1)
for(i =0; i<xdata.length; i++) {
name = xdata[i]
parent = ""
if(name.substr(name.length-1,1) == '/') {
xname = name.substr(0,name.length-1);
parent = xname.substr(0,xname.lastIndexOf("/")+1)
} else {
parent = name.substr(0,name.lastIndexOf("/")+1)
}
tree.core.data.push({ "id" : name, "parent" : parent, "text" : name })
}
console.log(tree);
I followed the alternative JSON format.
Result:
{
"core": {
"data": [
{
"id": "env/",
"parent": "#",
"text": "env/"
},
{
"id": "env/child1/env/key1",
"parent": "env/child1/env/",
"text": "env/child1/env/key1"
},
{
"id": "env/child1/key1",
"parent": "env/child1/",
"text": "env/child1/key1"
},
{
"id": "env/child1/key2",
"parent": "env/child1/",
"text": "env/child1/key2"
},
{
"id": "env/child1/",
"parent": "env/",
"text": "env/child1/"
},
{
"id": "env/child2/key1",
"parent": "env/child2/",
"text": "env/child2/key1"
},
{
"id": "env/child2/key2",
"parent": "env/child2/",
"text": "env/child2/key2"
},
{
"id": "env/child2/",
"parent": "env/",
"text": "env/child2/"
}
]
}
}
The above data missing parent "env/child1/env/" for child "env/child1/env/key1"
1. correct as follow:
data = [
"env/child1/env/"
"env/child1/env/key1",
"env/child1/key1",
"env/child1/key2",
"env/child1/",
"env/child2/key1",
"env/child2/key2",
"env/child2/",
"env/"
];
The complete code for parent getting the children's values as below:
https://github.com/peterhchen/700-jstree/blob/master/08_PathJSON/0802_PathChild2ParentValueHier.htm

Hierarchical json to flat with parent ID

I have Hierarchical JSON and want to convert to flat JSON without parent child.
vm.str = [
{
"s_gid": 0,
"title": "scholastic Master List 2016",
"nodes": [
{
"Id": "1",
"templateId": "1",
"s_gid": "10",
"m_s_p_id": "1",
"subject_group_name": "xxxxxxx",
"parent_id": "1",
"sname": "",
"nodes": [
{
"Id": "2",
"templateId": "1",
"s_gid": "100",
"m_s_p_id": "0",
"subject_group_name": "abc",
"parent_id": "10",
"sname": "",
"nodes": [
{
"Id": "3",
"templateId": "1",
"s_gid": "1000",
"m_s_p_id": "0",
"subject_group_name": "efg",
"parent_id": "100",
"sname": ""
}
]
}
]
}
]
}
]
what to convert to new vm.str2 = [] as flat, all nodes at same level without nodes ... sub nodes..
You can use recursive function to return one array of objects
var arr =[{"s_gid":0,"title":"scholastic Master List 2016","nodes":[{"Id":"1","templateId":"1","s_gid":"10","m_s_p_id":"1","subject_group_name":"xxxxxxx","parent_id":"1","sname":"","nodes":[{"Id":"2","templateId":"1","s_gid":"100","m_s_p_id":"0","subject_group_name":"abc","parent_id":"10","sname":"","nodes":[{"Id":"3","templateId":"1","s_gid":"1000","m_s_p_id":"0","subject_group_name":"efg","parent_id":"100","sname":""}]}]}]}]
function flatten(data) {
var result = [];
data.forEach(function(o) {
var obj = {}
for(var e in o) {
(Array.isArray(o[e])) ? result.push(...flatten(o[e])) : obj[e] = o[e];
}
result.push(obj)
})
return result;
}
console.log(flatten(arr))
You could use Array.prototype.reduce() plus recursion for this task:
function getNodes(inputArr) {
return inputArr.reduce(function (prev, value) {
return prev.concat(
[ value ],
(value.nodes ? getNodes(value.nodes) : [])
);
}, []);
}
If you still want to remove nodes, you could either use Array.prototype.map or even Array.prototype.each:
output = output.map(function (value) {
value.nodes = undefined;
return value;
});

How can this javascript object be reconstructed

I have an object type as below:
{
"1": {
"ref": "1",
"active": "1",
"showorder": "1",
"title": "Test 1"
},
"2": {
"ref": "2",
"active": "1",
"showorder": "2",
"title": "Test 2"
},
"3": {
"ref": "3",
"active": "1",
"showorder": "4",
"title": "Test 4"
},
"4": {
"ref": "4",
"active": "1",
"showorder": "9",
"title": "Test 9"
},
"5": {
"ref": "5",
"active": "1",
"showorder": "7",
"title": "Test 7"
}
}
On the basis of showorder property i need it to be arranged as follows:
{
"1": {
"ref": "1",
"active": "1",
"showorder": "1",
"title": "Test 1"
},
"2": {
"ref": "2",
"active": "1",
"showorder": "2",
"title": "Test 2"
},
"3": {
"ref": "3",
"active": "1",
"showorder": "3",
"title": "Test 3"
},
"4": {
"ref": "4",
"active": "1",
"showorder": "4",
"title": "Test 4"
},
"5": {
"ref": "5",
"active": "1",
"showorder": "5",
"title": "Test 5"
}
}
And here is my failed attempt thought i would pass the object to this function :
function reArrangeTilesObject(tilesObj){
var newObj = [];
for(var i in tilesObj){
var j = 1;
if(j == tilesObj[i].showorder){
newObj.push(tilesObj[i]);
j++;
}
}
return newObj;
}
Sorry if i am being unclear. The object is created in a random manner. So what i want is the object to be arranged as per the showorder property. so if showorder is 4 it should come in the key of 4 and not have the object of showorder 9. showorder 9 should come under the key of 9. Thanks
Steps:
Convert the object to an array (objects are unordered, arrays are ordered)
Sort the array
Code:
function reArrangeTilesObject(tilesObj) {
var tilesArray = [];
// Step 1 - convert to array
for (var i in tilesObj) {
tilesArray.push(tilesObj[i]);
}
// Step 2 - sort
tilesArray.sort(function(a, b) {
return a.showorder - b.showorder;
});
return tilesArray;
}
Result – an ordered array:
[
{"ref":"1","active":"1","showorder":"1","title":"Test 1"},
{"ref":"2","active":"1","showorder":"2","title":"Test 2"},
{"ref":"3","active":"1","showorder":"4","title":"Test 4"},
{"ref":"5","active":"1","showorder":"7","title":"Test 7"},
{"ref":"4","active":"1","showorder":"9","title":"Test 9"}
]
I may have misunderstood something but :
for (var i = 0; i < tilesObj; i++)
{
tilesObj[i].showOrder = i;
tilesObj[i].title = "Test "+i;
}
or
for (var i in tilesObj)
{
tilesObj[i].showOrder = tilesObj[i].ref;
tilesObj[i].title = "Test "+tilesObj[i].ref;
}
will do the job on the example I believe.
I can't quite understand if you're trying to rename the properties in the object array, or sort them into a new array.
If you're trying to sort:
function reArrangeTilesObject(tilesObj) {
var newObj = [];
for (var i = 1; i <= tilesObj.length; i++) {
for (var j in tilesObj) {
if (i == tilesObj[j].showorder) {
newObj.push(tilesObj[j]);
break;
}
}
}
return newObj;
}
Should add them to your newObj array based on their showorder property.
Try this one (demo):
function reArrangeTilesObject(tilesObj){
var result = {};
for(var key in tilesObj){
content = result[key] = tilesObj[key];
content.showorder = key;
content.title = "Test " + key;
}
return result;
}
It will return a new object in the original format (a Dictionary).
If you want to return an Array (and deal with possible empty indexes), just change var result = {}; into var result = [];
If you are just rewriting the showorder and title values this will work
function fix(o) {
for(var n in o) {
o[n].showorder = n;
o[n].title = "Test " + n;
}
}

Categories

Resources