javascript/jquery one object insert to another - javascript

I have two objects and I need one object inserted into other in the first row.
I found Javascript function splice, but i don't know how use it.
My code:
$(document).ready(function() {
var person = {};
person[0] = {};
person[0]['name'] = 'Joy';
person[0]['age'] = '12';
var personAll = {};
personAll[0] = {};
personAll[0]['name'] = 'Vanda';
personAll[0]['age'] = '49';
personAll[1] = {};
personAll[1]['name'] = 'Peter';
personAll[1]['age'] = '12';
var new_object = personAll.splice(0, person);
//I need get this result:
new_object[0]['name'] = 'Joy';
new_object[0]['age'] = '12';
new_object[1]['name'] = 'Vanda';
new_object[1]['age'] = '49';
new_object[2]['name'] = 'Peter';
new_object[2]['age'] = '12';
console.log(new_object);
});
How do I fix this code?

See the documentation.
splice() also takes the number of items to remove.
You need to call it like this:
array.splice(startIndex, howManyToRemove, newItems...);
In this case, you probably want to remove 0 items.
If you're inserting at the beginning of the array, you can also simply call unshift().

I notice you are indexing a OBJ. Splicing is done with arrays. I would make an array of objects, and then splice accordingly.
See also: http://www.w3schools.com/jsref/jsref_splice.asp

If you make person and personAll arrays, you can use the concat method.
var new_object = person.concat(personAll);

Splice method remove elements from array.
You need to use concat method, like this:
var person = {name: 'Joy', age: 12};
var persons = [{name: 'Vanda', age: 49}, {name: 'Peter', age: 12}];
var newPersons = [person].concat(persons);
console.log(newPersons);
Console output will be:

Related

Javascript finding combined properties from an array and object keys

I have an object. I would like to be able to dynamically create an array, then create another object that contains the key-value pairs that correspond with properties from the array that I created.
For example, if I have the following object...
var churchMembers = {
John: 'fsiolfjdklsjds#yahoo.com',
Betty: 'fowifj#hotmail.com',
Christopher: 'fsis#yahoo.com',
James: 'wfowji#gmail.com',
Deep: 'abab#msn.com'
};
and I create the following array:
var peopleComing = ['John', 'Christopher', 'James'];
I want the following response
var peopleList = {
John: 'fsiolfjdklsjds#yahoo.com',
Christopher: 'fsis#yahoo.com',
James: 'wfowji#gmail.com'
};
Right now I'm trying to use a for loop and all I'm doing is iterating through the object properties, which is not giving me anything. Going with the Object.keys route seems counterproductive, although that would easily allow me to filter out the correct names. Thanks. SIAP
You can use Array#forEach to iterate over your list of names, and get the email for each name and add it to your peopleList.
var peopleList = {};
peopleComing.forEach(function(name){
peopleList[name] = churchMembers[name];
});
Ignoring the typo you have in your code, the below code should be capable of initializing peopleList with what you want.
var churchMembers = {
John: "fsiolfjdklsjds#yahoo.com"
Betty: "fowifj#hotmail.com",
Christopher: "fsis#yahoo.com",
James: "wfowji#gmail.com",
Deep: "abab#msn.com"
},
peopleComing = ["John", "Christopher", "James"],
peopleList = {};
for (var i = 0, j = peopleComing.length; i < j; i++) {
peopleList[peopleComing[i]] = churchMembers[peopleComing[i]];
}

Push datas into a multidimensional array in JS

I'm trying to push some datas into my array.
Actually my code looks like this:
arr.push('step1||item1||99');
It works but it's not the best as I need to split it after to manager datas.
How can I transform this into a multidimensional array ?
What I tried:
arr = [];
arr['step'] = 'step1';
arr['name'] = 'item1';
arr['number'] = '99';
arr.push(arr);
But it doesn't work...
Any help please.
Is there a reason you don't want these individual data points to be objects?
var arr = [];
var dataPoint = { 'step': 'step1', 'name': 'item1', 'number': 99 };
arr.push(dataPoint);
If this isn't what you're looking for, can you give a fuller explanation of what your dataset should look like so we can better understand the problem?
Array holds "indexes"
Object holds "Key" and "Value"
Array example:
var arr = new Array;
arr[0] = 'step1';
arr[1] = 'item1';
arr[2] = '99';
console.log(arr);
Object example:
var obj = new Object;
obj.stop = 'step1';
obj.item = 'item1';
obj.number = 99;
console.log(obj);
Objects in array:
var arr = new Array;
var obj = new Object;
obj.stop = 'step1';
obj.number = 99;
arr.push(obj)
console.log(arr); // Output => [{stop: 'step1', number: 99}]
maybe you mean something like this
arr=[];
var s={
step:'step1',
name:'item1',
number:'99'
}
arr.push(s);
console.log(arr);
s is an object, which works just like an array, but is referenced by a string instead of an integer:
s['step'] === 'step1'
s.step === 'step1'
arr[0] === s
Be aware that there are some differences, like you can't iterate over an object like you can an array: you need to use another method like a "for in" loop, for instance.

How to merge the below arrays in javascript?

I have two arrays and I want to join them
function test()
{
var arr1 = [
{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},
{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}
];
var arr2 = [
{"Deptid":4,"Deptname":"IT"},
{"Deptid":1,"Deptname":"HR"},
{"Deptid":3,"Deptname":"HW"},
{"Deptid":24,"Deptname":"HW4"}
];
var res = Pack(arr1,arr2);
console.log(res);
}
function Pack()
{
var args = [].slice.call(arguments);
args.join(',');
return args;
}
I am expecting the output as
[{"Employees":[{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}],"Departments":[{"Deptid":1,"Deptname":"IT"},{"Deptid":2,"Deptname":"HR"},{"Deptid":3,"Deptname":"HW"},{"Deptid":4,"Deptname":"SW"}]}]
But not able to. How to do it?
I have already tried with Concat() function of Javascript but it didn't helped.
N.B.~ As it can be assumed that there can be variable number of arrays in the Pack function.
Couldn't you do something like:
var newArray = [ { "Employees": arr1, "Departments": arr2 } ]
Try this:
var arr1 = [
{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},
{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}
];
var arr2 = [
{"Deptid":4,"Deptname":"IT"},
{"Deptid":1,"Deptname":"HR"},
{"Deptid":3,"Deptname":"HW"},
{"Deptid":24,"Deptname":"HW4"}
];
var json = {};
var jsonArr = [];
json.Employees = arr1;
json.Department = arr2;
jsonArr.push(json);
document.write(JSON.stringify(jsonArr));
From the expected JSON, what you need is neither "merging", nor "concatenation". You want to put an array inside an object.
What you want is below:
var output = [{
"Employees": arr1,
"Department": arr2
}];
Note that output is an array according to your expectation. Why you need an array is something I dont understand.
Ok, so i put a little fiddle together for you, Here
Most of your code stays the same, except I added this to your test function:
var myObjToMerge = [{Employees:[]},{Departments:[]}];
var res = Pack(myObjToMerge,arr1,arr2);
You need to give 'Pack' some object to merge the arrays to, so I created an arbritary array of objects modeled after your example. Note that this array of objects can come from anywhere and this method doesn't require it to be known ahead of time like some of the other examples.
Then I changed the 'Pack' function:
function Pack()
{
var objToMerge = arguments[0];
for(var i = 0;i<objToMerge.length;i++)
{
if(arguments.length > i+1)
{
var firstProperty = Object.keys(objToMerge[i])[0];
objToMerge[i][firstProperty]= arguments[i+1];
}
}
return objToMerge;
}
The idea here is that 'Pack' grabs the first argument, your object to merge the remaining arguments into. I would suggest using function parameters, but that is your call.
Then, I iterate through the objects in the objToMerge array (there are two objects: Employees and Departments).
I assume that the remaining items in arguments is in the correct order and I grab the next item in arguments and assign to to the first property in the object I am currently looped in.
The line:
var firstProperty = Object.keys(objToMerge[i])[0];
Will return the string value of the first property in an object. We then use this to set the next array in arguments to that property:
objToMerge[i][firstProperty]= arguments[i+1];
there are a great deal of assumptions here and ways to improve, but you can see that it works in the fiddle and you can improve upon it as needed.
function test() {
var arr1 = {"Employees" : [
{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},
{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}
]};
var arr2 = {"Departments":[
{"Deptid":4,"Deptname":"IT"},
{"Deptid":1,"Deptname":"HR"},
{"Deptid":3,"Deptname":"HW"},
{"Deptid":24,"Deptname":"HW4"}
]};
var res = Pack(arr1,arr2);
console.log(res);
}
function Pack()
{
var results = [];
arguments.forEach(function(element){
results.push(element);
});
return results;
}

Stringify with multidimensional array gives empty result

I have an array like this:
var d = new Array();
d[0] = new Array();
d[0]['item1'] = '123';
d[0]['item2'] = '456';
d[0]['item3'] = '789';
d[1] = new Array();
d[1]['item1'] = '123';
d[1]['item2'] = '456';
d[1]['item3'] = '789';
When using console.log(JSON.stringify(d)); my console logs "[[],[]]"
Why does JSON.stringify() give an empty result?
Here's a jsFiddle showing my current situation
I read this. The answer is a solution, however my attribute names are variable, as you can see in the jsFiddle. Is there a way to make an attribute's name variable? Like this (doesn't work obviously):
var s = 'attrName';
var object = {
s: '123'
}// The object should have an attribute named attrName
Try:
d[0] = {};
instead of:
d[0] = new Array();
This way d[0] is an object and not an array.
Working example: http://jsfiddle.net/FLDfR/
This is happening because you are confusing arrays and objects.
While it is true that in JavaScript, arrays are just special objects but they are treated somewhat differently.
While this isn't technically true, pretend that arrays can only take integer keys, between 0 and 2^53.
// Tested in the console.
var d = [];
d[0] ={};
d[0]['item1'] = '123';
d[0]['item2'] = '456';
d[0]['item3'] = '789';
d[1] = {};
d[1]['item1'] = '123';
d[1]['item2'] = '456';
d[1]['item3'] = '789';
alert(JSON.stringify(d));
will do what you want.
Going along with Jeremy J Starcher, you could just go full object with it:
var data = {
'0': {
'item1': '123'
},
'1': {
'item1': 'abc'
}
};
This will give you a better outcome, though not technically an array. =/
To make the dynamic attribute you can use [] something like
var s = 'attrName';
var object = {};
object[s] = '123';
DEMO

jquery json .. sort data array custom list .. how?

I want sort values ​​by array Another
for example
var objName = [{id:1, name:"one"},{id:2, name:"two"}, {id:3, name:"three"}];
var sortById = [1,3,2];
I want this output in that order
1 one
3 three
2 two
Stuff objName elements into a hash (i.e. object) indexed by id, then map the sortById array onto the hash values.
Exact code left as an exercise for the reader.
sorted=new Array()
for(var id_index=0;id_index<sortById.length;id_index++)
{
for(var obj_index=0;obj_index<objName.length;obj_index++){
if (objName[obj_index].id===sortById[id_index]) sorted.push(objName[obj_index])
}
}
//now sorted is the new sorted array. if you want to overwrite the original object:
objName=sorted;
Supposing that the length of both arrays are the same you can first create a hash:
var objName = [{id:1, name:"one"},{id:2, name:"two"}, {id:3, name:"three"}];
var myHash = {};
for(var i = 0; i<objName.length;i++){
myHash[objName[i].id] = objName[i];
}
Once you have this hash, you can loop over your keys array and get the values out:
var sortById = [1,3,2];
var sortedArray = [];
for(var i = 0; i<sortById.length;i++){
sortedArray.push(myHash[sortById[i]]);
}
Something clear and readable (subjective, probably not for everyone):
var result = [];
sortById.forEach(function(id) {
result = result.concat(objName.filter(function(i) {
return i.id == id;
}));
});
JSFiddle: http://jsfiddle.net/RLH6F/
Implemented just for fun.
Warning: O(n^2)
PS: I agree it would be better just give the recipe without the code, but as soon as there are already community members provided the copy-paste solutionы I decided to provide at least a nice looking one.

Categories

Resources