Javascript finding combined properties from an array and object keys - javascript

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]];
}

Related

storing key value pairs in an array in javascript

I have 2 arrays namely,
configdata = ["assignee", "shortDesc"];
ticketarray = ["Tom","testDesc"];
I want to store the values as a key value pair in another array, something like this:
ticketData = ["assignee":"Tom","shortDesc":"testDesc"];
Kindly note that the array values are dynamic, so I cannot hardcode them.
Is there a way to do so? I am able to achieve the above said requirement but the length always shows 0. This is the code that I am using:
configdata.Incident_Field.forEach(function (k, i) {
this[k] = ticketarray[i];
}, ticketData);
Other people have explained why your code did not work. I am providing another solution using reduce.
const configdata = ["assignee", "shortDesc"];
const ticketarray = ["Tom", "testDesc"];
let ticketData = configdata.reduce((result, value, index) => {
result[value] = ticketarray[index];
return result;
}, {});
console.log(ticketData);
Output:
{
assignee: "Tom",
shortDesc: "testDesc"
}
The below is not a valid structure in JavaScript:
ticketData = ["assignee":"Tom","shortDesc":"testDesc"];
What you need is a JavaScript object. The best you can do is:
Make sure both the array lengths are same.
Associate the key and value by creating a new object.
Use Object.keys(obj).length to determine the length.
Start with the following code:
configdata = ["assignee", "shortDesc"];
ticketarray = ["Tom", "testDesc"];
if (configdata.length == ticketarray.length) {
var obj = {};
for (var i = 0; i < configdata.length; i++)
obj[configdata[i]] = ticketarray[i];
}
console.log("Final Object");
console.log(obj);
console.log("Object's Length: " + Object.keys(obj).length);
The above will give you an object of what you liked, a single variable with all the values:
{
"assignee": "Tom",
"shortDesc": "testDesc"
}

How can I push an object into an array?

I know it's simple, but I don't get it.
I have this code:
// My object
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
nietos.push(nieto.label);
nietos.push(nieto.value);
If I do this I'll get a simple array:
["Title", "Ramones"]
I need to create the following:
[{"01":"Title", "02": "Ramones"}]
How can I use push() to add the object into the nietos array?
You have to create an object. Assign the values to the object. Then push it into the array:
var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);
Create an array of object like this:
var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;
First you create the object inside of the push method and then return the newly created array.
can be done like this too.
// our object array
let data_array = [];
// our object
let my_object = {};
// load data into object
my_object.name = "stack";
my_object.age = 20;
my_object.hair_color = "red";
my_object.eye_color = "green";
// push the object to Array
data_array.push(my_object);
Using destructuring assignment (ES6)
const nieto = {label: 'title', value: 'ramones' }
const modifiedObj = {01: nieto.label, 02: nieto.value}
let array = [
{03: 'asd', 04: 'asd'},
{05: 'asd', 06: 'asd'}
]
// push the modified object to the first index of the array
array = [modifiedObj, ...array]
console.log(array)
If you'd like to push the modified object to the last index of the array just change the destructured array ...array to the front.
array = [...array, modifiedObj]
Well, ["Title", "Ramones"] is an array of strings. But [{"01":"Title", "02", "Ramones"}] is an array of object.
If you are willing to push properties or value into one object, you need to access that object and then push data into that.
Example:
nietos[indexNumber].yourProperty=yourValue; in real application:
nietos[0].02 = "Ramones";
If your array of object is already empty, make sure it has at least one object, or that object in which you are going to push data to.
Let's say, our array is myArray[], so this is now empty array, the JS engine does not know what type of data does it have, not string, not object, not number nothing. So, we are going to push an object (maybe empty object) into that array. myArray.push({}), or myArray.push({""}).
This will push an empty object into myArray which will have an index number 0, so your exact object is now myArray[0]
Then push property and value into that like this:
myArray[0].property = value;
//in your case:
myArray[0]["01"] = "value";
I'm not really sure, but you can try some like this:
var pack = function( arr ) {
var length = arr.length,
result = {},
i;
for ( i = 0; i < length; i++ ) {
result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
}
return result;
};
pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}
The below solution is more straight-forward. All you have to do is define one simple function that can "CREATE" the object from the two given items. Then simply apply this function to TWO arrays having elements for which you want to create object and save in resultArray.
var arr1 = ['01','02','03'];
var arr2 = ['item-1','item-2','item-3'];
resultArray = [];
for (var j=0; j<arr1.length; j++) {
resultArray[j] = new makeArray(arr1[j], arr2[j]);
}
function makeArray(first,second) {
this.first = first;
this.second = second;
}
This solution can be used when you have more than 2 properties in any object.
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
let xyz = Object.entries(nieto)
xyz.forEach((i,j)=>{
i[0] = `${(j+1).toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}`
})
nietos.push(Object.fromEntries(xyz))

An object contains a collection of objects - each with an id and name, how do I separate them?

At the moment I have this object:
obj = [object{id: 1, name: test, parentID: 3}, object{id:1, name: another, parentID: 5}, object{id:2, name:something, parentID: 1}].
Ultimately I want an object structured in a different manner.
So that it is object, but if my identifier is 1, it has a collection of names (in this case test, and another). If it is 2, it only shows 'something'.
I can't work out how this should look, probably like so?
obj = [[1,test], [1,another], [2,something]] right?
So that if I call obj[1] I get a multiples back (test, another etc).
Can someone help? I've been fiddling with this for an hour now, I just don't understand.
I built the original object like this:
var obj = Array();
//loop here
var obj = {
id: id,
name: name,
parentID: parentID
};
obj.push(obj);
What did I do wrong? How can I fix this? This got me my object within objects thing, but really I want id's and names within id's and names. My ultimate goal is to iterate through this. So that I only get out the names of anything of a like ID, that way I can use this to populate an array or count
Thus:
if(obj[id] == 1){
//put the name in the new array
}
is my ultimate goal. But I've gotten a bit lost with the initial object creation so now it is a big mess.
Try:
var obj = [{id: 1, name: "Foo"}, {id: 2, name: "Fee"}, {id: 3, name: "Fii"}];
var result = [], item, i = 0;
while(item = obj[i++]){
for(key in item){
if(key === "id") continue; //remove this line if you want to keep the ID also in the array
!result[i] && (result[i] = []);
result[i].push(item[key]);
}
}
console.log(result[1]); // --> ["Foo"]
My take:
var sourceObject=[{id:0,name:'Tahir'},{id:0,name:'Ahmed'},{id:1,name:'David'},{id:1,name:'G'},{id:2,name:'TA'},{id:3,name:'DG'}];
function getNames(id){
var names=[],length=sourceObject.length,i=0;
for(i;i<length;i+=1){
if(sourceObject[i].id===id){
names[names.length]=sourceObject[i].name;
}
}
return names;
}
console.log(getNames(1));
What you want to do is walk the array of objects one time. Each time through, you want to check your new object to see if that id exists yet. If it does, add the name. If not, make a new entry for that id and add an array with one entry. Note, this doesn't handle duplicate names (it just adds it again).
var array = [{id:1, name:"test"},
{id:1, name:"another"},
{id:2, name:"something"}];
var result = {};
array.forEach(function(item) {
if (result[item.id]) {
result[item.id].push(item.name);
}
else {
result[item.id] = [item.name];
}
});
console.log(result[1]);

javascript/jquery one object insert to another

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:

turn json row-items into nested javascript objects array

Given the following array of json objects:
var items = [
{id:1, parentId:0, name:'item1'},
{id:2, parentId:1, name:'item1.2'},
{id:3, parentId:1, name:'item1.3'},
{id:4, parentId:3, name:'item3.4'},
{id:5, parentId:3, name:'item3.5'},
...more nesting, levels, etc.
];
And a base object like:
var myObj = function(id, parentId, name, children){
this.id = id;
this.parentId = parentId;
this.name = name;
this.children = children;
};
how do I use recursion to loop through this items array and build a new array like so:
var newArray = [
new myObj(1, 0, 'item1', [
new myObj(2, 1, 'item1.2', []),
new myObj(3, 1, 'item1.3', [
new myObj(4, 3, 'item3.4', []),
new myObj(5, 3, 'item3.5', [])
])
]);
];
any help is greatly appreciated
edit:
the parent/child relationship can be infinite. so i'm looking for a recursion function that would convert the first "items" array into the second "newarray"
The title of your question is a bit misleading. You're trying to convert an array of items into a tree-like nested object.
Your use of the Object constructor is a bit redundant. Use quasi-literal notation ({foo:bar}) instead. Actually, you don't even need to create new objects, you can use the original ones.
First, convert the list to an object to facilitate referencing by id:
var map = {}
for (var i = 0; i < items.length; i++) {
map[items[i].id] = items[i];
}
Now, iterate through the items and add children array:
var newArray = [];
for (id in map) {
var item = map[id];
var parent = map[item.parentId];
if (parent) {
parent.children = parent.children || [];
parent.children.push(item); // add reference to item
} else { // root
newArray.push(item);
}
}
Note that this modifies the original items array, and newArray holds pointers to its entries. If you don't want that, create a copy of items first.
I don't know if this helps, but in this fiddle there's an iterative solution that creates that newArray. Using a json obj as an array and then adding the children as you iterate over the items array.

Categories

Resources