Modification of array objects - javascript

I am trying to rebuild an array ,so I need suggestion on doing it using best practices.
I have an array object as follows:
MainObject:
0:"Namebar"
1: Object
Name: "Title1"
Url: "Url1"
2: Object
Name: "Title2"
Url: "Url2"
3: Object
Name: "Title3"
Url: "Url1"
In the above since the "url" is same , I want to group it same object and I am expecting the output in the following format:
0: "Url1"
1: Object
Name : "Title1"
Url: "Namebar"
2: Object
Name : "Title3"
Url: "Namebar"
1: "Url2"
1: Object
Name : "Title2"
Url: "Namebar"
I am trying to have two arrays and loop through the MainObject for swapping the items which I know is not only a teadious process but very much high on time complexity.
For example like :
var extract1 = MainObject[0];
var extract2 = using for loop to extract and swap ......
I am not getting any other way of achieving this. Any approach for this in javascript/jquery?

This should do the job:
var extract1 = MainObject[0];
var newArray = {};
var newArrProp;
var extract1Props = Object.keys(extract1);
for( i = 0; i< extract1Props.length; i++)
{
newArrProp = extract1Props[i];
var nestedObjects = extract1[newArrProp];
for(j = 0; j < nestedObjects.length; j++)
{
if(!newArray[nestedObjects[j].Url])
{
newArray[nestedObjects[j].Url] = [];
}
newArray[nestedObjects[j].Url].push({Name:nestedObjects[j].Name,Url:newArrProp});
}
}
Working fiddle

You could use some loops.
var MainObject = [{ "Namebar": [{ Name: "Title1", Url: "Url1" }, { Name: "Title2", Url: "Url2" }, { Name: "Title3", Url: "Url1" }] }],
object2 = [];
MainObject.forEach(function (a) {
Object.keys(a).forEach(function (k) {
a[k].forEach(function (b) {
var temp = {};
if (!this[b.Url]) {
temp[b.Url] = [];
this[b.Url] = temp[b.Url];
object2.push(temp);
}
this[b.Url].push({ name: b.Name, Url: k });
}, this);
}, this);
}, Object.create(null));
document.write('<pre>object2 ' + JSON.stringify(object2, 0, 4) + '</pre>');
document.write('<pre>MainObject ' + JSON.stringify(MainObject, 0, 4) + '</pre>');

Related

loop through objects and find specified properties

I have an array of objects. A typical object looks like:
{
id: x
name: y
employeeInfo: {
employeeNumber: x
startDate: x
}
salary: x
}
Now I'm trying to loop through it and get the name, employeeNumber and salary.
My column variable, to be used in the loop, is:
public columns: Array<any> = [
{title: 'id', name: 'id'},
{title: 'employeeInfo.employeeNumber', name: 'employeeInfo.employeeNumber'},
{title: 'salary', name: 'salary'}]
I'm trying to loop with
item[column.name]
but of course this would result in item['emplyeeInfo.employeeNumber'], which would result in a undefined.
Can someone help?
You can split the column name and reduce, like:
column.name.split('.').reduce((res, part) => res[part], item)
split returns an array (in our case ['employeeInfo', 'employeeNumber']) so we can reduce that array using the item as the initialValue.
The reduce() method applies a function against an accumulator and each
element in the array (from left to right) to reduce it to a single
value.
Something like this:
var employees = [
{
id: 1,
name: 'Charlie',
employeeInfo: {
employeeNumber: 123,
startDate: '2017-01-23'
},
salary: 2500
},
{
id: 2,
name: 'John',
employeeInfo: {
employeeNumber: 456,
startDate: '2017-02-26'
},
salary: 3500
}
];
var columns = [
{title: 'id', name: 'id'},
{title: 'employeeInfo.employeeNumber', name: 'employeeInfo.employeeNumber'},
{title: 'salary', name: 'salary'}
];
function buildTable() {
var table = $("<table>");
var header = $("<tr>");
for(var i = 0; i < columns.length; i++) {
header.append("<th>" + columns[i].title + "</th>");
}
table.append(header);
for(var i = 0; i < employees.length; i++) {
var employee = employees[i];
var row = $("<tr>");
for(var y = 0; y < columns.length; y++) {
var properties = columns[y].name.split('.');
var value = employee;
for(var x = 0; x < properties.length; x++) {
value = value[properties[x]];
}
row.append("<td>" + value + "</td>");
}
table.append(row);
}
$("#result").append(table);
}
buildTable();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Can't you just parse/split the name on the dot and for each part, you get the object, fetch its property and reiterate while there is a next property to fetch?
I ended up using a "simplify" approach. i.e. filter through the array, grab what I need, put it in a new object, put it in a temporary array and finally replace the complex array with the simple array.
try this:
var myObject = {
id: "x",
name: "y",
employeeInfo: {
employeeNumber: "inner employeeNumber",
startDate: "inner date",
},
salary: "x"
}
for(var id in myObject) {
if(typeof myObject[id] === "object") {
for(var innerId in myObject[id]){
console.log(innerId + ": " + myObject[id][innerId]);
}
} else {
console.log(id + " " + myObject[id]);
}
}

Loop at JSON array and create a single JSON string

This should be easy but for some reason I'm stuck -
if I have a json like this and need to convert it:
{ data : [
{id : data1, name : "Description"},
{id : data2, name : "Contribution"},
{id : data3, name : "Footer"},
]}
into something like this?
{
data : [
{ data1: "Description" , data2: "Contribution", data3: "Footer" },
]}
Thanks,
Stuart
A small Array.prototype.reduce should do the job:
var obj = {
data: [
{ id: 'data1', name: 'Description' },
{ id: 'data2', name: 'Contribution' },
{ id: 'data3', name: 'Footer' },
]
};
obj.data = obj.data.reduce(function (r, a) {
r[a.id] = a.name;
return r;
}, {});
document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');
You can use a for loop over the array.
var newData = [];
for(var i=0;i<data['data'].length;i++){
var obj={};
obj[data['data'][i]['id']]=data['data'][i]['name'];
newData.push(obj);
}
console.log(newData);
Refer fiddle
Updated Answer
var newArray = data['data'].map(function(obj){
var rObj = {};
rObj[obj.id] = obj.name;
return rObj;
});
You can use Array.map method for that also.
Refer fiddle-map
You can try to use the underscore.js lib.
Then check this example for your desired result Group By
Enjoy ;-)
var array=[];
for(int i=0; i<data.length; i++){
var object={};
object[data[i].id=data[i].name];
array.push(obj);
}
You can do it almost in a single line using lodash:
var obj1 = { data : [
{id: "data1", name: "Description"},
{id: "data2", name: "Contribution"},
{id: "data3", name: "Footer"},
]};
var obj2 = {
data: _.zipObject(_.pluck(obj1.data, "id"),
_.pluck(obj1.data, "name"))
}
document.write(JSON.stringify(obj2, null, 2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
Have a look at _.pluck and _.zipObject.
You can also use underscore but lodash is faster, more complete, and you can create custom build with only what you need.

How to retrieve first value from Array objects into a new Array in Javascript?

I have a Javascript Array of objects as follows
var data = [
{
id: 1,
date : '1/1/2011',
todo : 'Maths'
},
{
id: 2,
date : '1/1/2012',
todo : 'Science'
} ................. and soo on
];
I want a resulting data as
var newArray = [
['1/1/2011', '1/1/2012'],
[
{
id:1,
todo: 'Maths'
},
{
id:2,
todo: 'Science'
}
]
]
How can I do that in Javascript efficiently ?
function prepare(data) {
var result = [ [], [] ];
for(var i = 0; i < data.length; i++) {
result[0][i] = data[i].date;
result[1][i] = { id: data[i].id, todo: data[i].todo };
}
return result;
}
var newArray = prepare(data);
try
var data = [{
id: 1,
date: '1/1/2011',
todo: 'Maths'
}, {
id: 2,
date: '1/1/2012',
todo: 'Science'
}];
var array = [];
data.forEach(function (item) {
array.push(item.date);
delete item.date;
})
data.unshift(array)
console.log(data)
I have tried. Its working
var data = [
{
id: 1,
date : '1/1/2011',
todo : 'Maths'
},
{
id: 2,
date : '1/1/2012',
todo : 'Science'
}];
var newArray=formatStr(data);
alert(JSON.stringify(newArray));
function formatStr(data){
arr1=[];
var arr2=[];
for (var i in data) {
var obj={};
obj["id"]=data[i].id;
obj["todo"]=data[i].todo;
arr1.push(data[i].date);
arr2.push(obj);
}
var result=[arr1,arr2];
return (result);
}
If you can use jQuery, then this will work:
var newArray = [[], data];
$.each(data, function(i,v) {newArray[0].push(v.date);delete v.date;});
For pure javascript, this will work:
var newArray = [[], data];
for (var i=0; i<=data.length; i++) {
typeof data[i]==="object" ? (newArray[0].push(data[i].date), delete data[i].date) : '';
}

Javascript array format for charts

I have two arrays
A =[1990,1991,....]
B=[a,b,c,d,e,f,...]
I want the resultant array in this format
Resultant=[{
name: 1990,
data: [a,b,c]
},{
name: 1991,
data: [d,e,f]
},...
]
Please help me how will I make it using for loops?
How about this:
var b= ["a","b","c","d","e","f"];
var result = [1990,1991].map(function(n){ return { name:n, data: b.splice(0,3)} });
This will format data with Array.prototype.map, based on your (rather vague) requirement:
var A = [1990,1991];
var B = ["a","b","c","d","e","f"];
var formatted = A.map(function (name, i) {
return {
name: name,
data: B.slice(i*3, i*3+3)
}
});
/*[
{
"name": 1990,
"data": [
"a",
"b",
"c"
]
},
{
"name": 1991,
"data": [
"d",
"e",
"f"
]
}
]*/
Assuming that for each in A, you want data to store 3 elements of B. I've stuck with your requirement of using for loops.
var Resultant = [];
for (var i = 0; i < a.length; i++) {
var data = [];
for (var j = 0; j < 3, B.length > 0; j++) {
data.push(B.shift());
}
Resultant.push({name: A[i], 'data': data});
}
This worked for me:
http://jsfiddle.net/s5zdD/ <-- see jsfiddle to show
A =[1990,1991,1992];
B=['a','b','c','d','e','f','g','h','i'];
var Resultant = jQuery.map(A, function(i,v){
// if no jQuery use:
// var Resultant = A.map(function(i,v){
return {
'name':A[v],
'data': B.splice(0,3)
}
})
console.log(Resultant);

Updating an array of objects in javascript

I have an array of javascript objects like the following:
var food = [
{id: 1, name: 'Apples', owned: true },
{id: 2, name: 'Oranges', owned: false },
{id: 3, name: 'Bananas', owned: true }
];
Then I receive another array with the following data:
var newFood = [
{id: 1, name: 'Peas'},
{id: 2, name: 'Oranges'},
{id: 3, name: 'Bananas'},
{id: 4, name: 'Grapefruits'}
];
How can I update the previous food array with the new information in newFeed, without overwriting the original owned property, while adding an owned: false to any new object?
Keep in mind this is plain javascript, not jQuery.
You'd probably want to index food by id so make food an object instead of an array:
var food = {
1: {name: "Apples", owned: true},
//...
}
then iterate over newFood and update the fields appropriately.
I think you can use underscore.js for fix the problem.
var arrayObj = [
{Name:'John',LastName:'Smith'},
{Name:'Peter',LastName:'Jordan'},
{Name:'Mike',LastName:'Tyson'}
];
var element = _.findWhere(arrayObj, { Name: 'Mike' });
element.Name="SuperMike";
console.log(arrayObj);
This works:
var temp = {};
for (var i = 0, l = food.length; i < l; i += 1) {
temp[food[i].name] = true;
}
for (var i = 0, l = newFood.length; i < l; i += 1) {
if ( !temp[newFood[i].name] ) {
food.push( { id: food.length + 1, name: newFood[i].name, owned: false });
}
}
The first for statement will populate the temp object with the fruit names from the food array, so that we know which fruits exist in it. In this case, temp will be this:
{ "Apples": true, "Oranges": true, "Bananas": true }
Then, the second for statement checks for each fruit in newFood if that fruit exists in temp, and if it doesn't, if pushes a new array item into the food array.
some thing like this? JSFiddle Example
JavaScript
function updateFood( newFood, oldFood ) {
var foodLength = oldFood.length - 1;
for (var i = 0; i < newFood.length; i++) {
if (i > foodLength) { //add more if needed
newFood[i].owned = false;
oldFood.push(newFood[i]);
} else if (!food[i].owned) { //replace if needed
newFood[i].owned = false;
oldFood[i] = newFood[i];
}
}
}

Categories

Resources