Dynamically insert object into existing object - javascript

Lets say I have a simple model, like this:
var person = {
name: "Bob",
age: "30"
}
But how would I go about inserting a new object into the existing one? Say I make a new object:
var pets = [{name: "Lucky", type: "Dog"}, {name: "Paws", type: "Cat"}];
I will need to dynamically generate various models and insert them into various sections of my model.
My final model would look like this:
var person = {
name: "bob",
age: "30",
pets: [
{name: "Lucky", type: "dog"},
{name: "Paws", type: "Cat"}
]
};

I'm not sure I completely understand your question, but how I understand it, all you need to do is set a new attribute of person.
var person = {
name: "Bob",
age: "30"
},
pets = [{ name: "Lucky", type: "Dog" }, { name: "Paws", type: "Cat" }];
person.pets = pets;
console.log(person); // Object: (String) name, (String) age, (Array) pets;
You could also use EMCAScript 5's Object.create() method.

create an array within person:
person.pets = [
{name: "Lucky", type: "dog"},
{name: "Paws", type: "Cat"}
];
or
var pets = [{name: "Lucky", type: "Dog"}, {name: "Paws", type: "Cat"}];
person.pets = pets;

Related

How can I convert an array of objects into an array of objects with the same values but with modified keys?

I have an array with objects and want to convert this to an array containing the same values but with different key names. (JavaScript)
For example, an array of
[{name: "Bob", age: 50, person: true}, {name: "Jerry", age: 20, person: true}]
becomes
[{identification: "Bob", years: 50, person: true}, {identification: "Jerry", years: 20, person: true}]
Using the Map function works perfectly here.
const people = [
{name: "Bob", age: 50, person: true},
{name: "Jerry", age: 20, person: true}
];
const formatted = people.map((person) => ({
identification: person.name,
years: person.age,
person: person.person
});
This should work for this problem.
I think that you may use the map method this method returns and array with the same length as the one you are mapping:
const array = [{name: "Bob", age: 50, person: true}, {name: "Jerry", age: 20, person: true}];
let newKeysArray = array.map( a => {
let obj = {
identification: person.name,
years: person.age,
person: person.person
};
return obj
} );
So inside the map you are assigning the values that you need to a new object and return the object as the mapped item.
Just in case you prefer to modify the objects in place, you can make use of a strategy by nverba here:
let rows = [
{name: "Bob", age: 50, person: true},
{name: "Jerry", age: 20, person: true}
];
let keyMaps = [
['name', 'identification'],
['age', 'years'],
];
for(let keyMap of keyMaps)
for(let row of rows)
delete Object.assign(row, {[keyMap[1]]: row[keyMap[0]] })[keyMap[0]];
console.log(rows);
keyMap[1] is the new key. keyMap[0] is the old key. Object.assign takes the value of the old key and places it in the new key. The delete keyword is confusing, but it doesn't apply to row as a whole. It's only deleting the old key.

Javascript array of objects - filter by uniqueness of specific key, and keep only certain keys

I'm sure this question has been asked in some form here before, but I am having trouble finding the right solution. I have an array of objects like this:
[
{id:"124", name:"Joe", lname:"Smith", age:"14"},
{id:"124", name:"Joe", lname:"Smith", age:"17"},
{id:"124", name:"Joe", lname:"Smith", age:"21"},
{id:"128", name:"Tom", lname:"Cans", age:"18"},
{id:"132", name:"Mik", lname:"Brak", age:"21"}
];
and I would like to shorten this array so that it only includes objects with unique id keys, as well as only the keys id, name, lname. The output I'm going for then is:
[
{id:"124", name:"Joe", lname:"Smith"},
{id:"128", name:"Tom", lname:"Cans"},
{id:"132", name:"Mik", lname:"Brak"}
];
What I've done so far - I can use the following code snippet to create an array of unique IDs, but that isn't getting me to where I need to go:
let uniqueIDs = [... new Set(mydata.map(val => val.id))];
Any help is appreciated!!
Store your array items in an object, indexed by id, and skip any which you already have:
var obj = {}
[ {id:"124", name:"Joe", lname:"Smith", age:"14"},
{id:"124", name:"Joe", lname:"Smith", age:"17"},
{id:"124", name:"Joe", lname:"Smith", age:"21"},
{id:"128", name:"Tom", lname:"Cans", age:"18"},
{id:"132", name:"Mik", lname:"Brak", age:"21"}
].forEach(function(d){
if ( ! obj[d.id] ) {
// omit the info you're not interested in
obj[d.id] = { id: d.id, name: d.name, lname: d.lname }
}
})
var uniq = Object.values(obj);
console.log(uniq)
You could take a Set of JSON strings and map them by parsing it.
var array = [{ id: "124", name: "Joe", lname: "Smith", age: "14" }, { id: "124", name: "Joe", lname: "Smith", age: "17" }, { id: "124", name: "Joe", lname: "Smith", age: "21" }, { id: "128", name: "Tom", lname: "Cans", age: "18" }, { id: "132", name: "Mik", lname: "Brak", age: "21" }],
unique = Array.from(
new Set(array.map(({ id, name, lname }) => JSON.stringify({ id, name, lname }))),
JSON.parse
);
console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }
First step is to create a data structure where you can be sure your entries are unique. I like reduce to convert an array to a map.
const arrayToMap = array.reduce((obj, { id, name, lname}) => ({ ...obj, [id]: { id, name, lname }), {});
Then you need to build the map to an array by iterating over the keys.
const mapToArray = Object.keys(arrayToMap).map(key => ({ ...arrayToMap[key] });
Here's an approach using Set and filter to remove duplicate id keys and map to remove the age key:
const data = [
{id: "124", name: "Joe", lname: "Smith", age: "14"},
{id: "124", name: "Joe", lname: "Smith", age: "17"},
{id: "124", name: "Joe", lname: "Smith", age: "21"},
{id: "128", name: "Tom", lname: "Cans", age: "18"},
{id: "132", name: "Mik", lname: "Brak", age: "21"},
];
const ids = new Set(data.map(e => e.id));
const result = data
.filter(e => ids.delete(e.id))
.map(({id, name, lname}) => ({id, name, lname}))
;
console.log(result);

Add new value into json

I'm tiying to build an excel uploader app. Right now, I can get the data from the excel file and send it to an API to store the info.
But i need something else, and is to asign to each value the id of the excel, which i'll get after save it first.
This is how i get the excel data before store it:
$scope.loadWorksheet = function(e){
var file = e.target.result;
var workbook = XLSX.read(file, { type: "binary" });
var sheetName = workbook.SheetNames[0];
$scope.sheet = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);
console.log($scope.sheet);
$scope.$apply();
};
Let's say i get the next array:
[{Name: "Chuck", Age: "30"},
{Name: "Marcus", Age: "18"},
{Name: "Shelly", Age: "29"}]
How can i add to each record the id of the document?
Per example, after save the document i get on the response the id:
$scope.IdDocument = 15;
And what i need is to put it on every record, like this:
[{Name: "Chuck", Age: "30", DocumentId: "15"},
{Name: "Marcus", Age: "18" DocumentId: "15"},
{Name: "Shelly", Age: "29" DocumentId: "15"}]
There's a way to do that? Hope you can help me.
I'm using AngularJs and Javascript.
You need forEach, with angularjs you can use angular.forEach
DEMO
var array = [{Name: "Chuck", Age: "30"},
{Name: "Marcus", Age: "18"},
{Name: "Shelly", Age: "29"}];
array.forEach(function(obj) { obj.DocumentId = "15"; });
console.log(array);
Use map function.It will return the updated array
var oldArray = [{
Name: "Chuck",
Age: "30"
},
{
Name: "Marcus",
Age: "18"
},
{
Name: "Shelly",
Age: "29"
}
];
var newArray = oldArray.map(function(item) {
item.DocumentId = '15';
return item;
})
console.log(newArray)
You can just iterate over your array and add the field as follows
var people = [{Name: "Chuck", Age: "30"},
{Name: "Marcus", Age: "18"},
{Name: "Shelly", Age: "29"}
];
people.forEach(p => p.DocumentId = "15");
console.log(people)
iterate over your array object using for loop
var people = [{Name: "Chuck", Age: "30"},
{Name: "Marcus", Age: "18"},
{Name: "Shelly", Age: "29"}];
for(var i=0 ; i<people.length;i++){
people[i].age = "10";
}

js object which should store list of objects as property

If I have one object myObj
and I want that object to have property clients which will hold list of clientObjects with Id and Name properties
var client= { Id: ", Name: "};
var myObj= {
clients: ????
}
how can I populate client properties and use it in myObj.clients
Please review this one:
//Following is Array of Client (aka object). Thats all you need
var clientList = [
{ Id: "id1", Name: "Name1"},
{ Id: "id2", Name: "Name2"},
{ Id: "id3", Name: "Name3"},
{ Id: "id4", Name: "Name4"},
{ Id: "id5", Name: "Name5"}
];
//and you can iterate through it in many ways, like this:
clientList.forEach(function(client) {
console.log(`Client Id:${client.Id} Name:${client.Name}`);
})
May be this is what you want
var myObj = {}; // Your 'myObj' object
// 'clients' property which will hold list of clientObjects
myObj.clients = [{
id: "1",
Name: "name1",
}, {
id: "2",
Name: "name2"
}];
console.log(myObj);
May be this will help you.....
var myObject = {clients:[]};
myObject.clients.push({id:"1",name:"name"});
myObject.clients.push({id:"2",name:"name"});
console.log(myObject);

sort array of objects based on string

Suppose we have an array like
var a = [
{ name: 'Tom', surname: 'TestAsIvanov' },
{ name: 'Kate', surname: 'Ivanova' },
{ name: 'John', surname: 'Alivanov' },
{ name: 'Ivan', surname: 'Ivanov' }
]
I need to sort this array by surname field based on a provided string, e.g.:
for 'iva' the pattern array should be sorted as follows
var newA = [
{ name: 'Ivan', surname: 'Ivanov' },
{ name: 'Kate', surname: 'Ivanova' },
{ name: 'John', surname: 'Alivanov' },
{ name: 'Tom', surname: 'TestAsIvanov' },
]
for 'a' the pattern array should be sorted as follows
var newA = [
{ name: 'John', surname: 'Alivanov' },
{ name: 'Ivan', surname: 'Ivanov' },
{ name: 'Kate', surname: 'Ivanova' },
{ name: 'Tom', surname: 'TestAsIvanov' },
]
So arrays should be ordered by string pattern provided. How is it possible to implement this?
I've made a simple sort script for that. I don't know if it is the best way because I had to use two sort() methods, one to sort alphabetically(taken from here) and another to simulate a LIKE 'string%'(comparing to SQL) to get your condition:
var queryString = "iva";
a = a.sort(function(a, b) {
var s1 = a.surname.toUpperCase().indexOf(queryString.toUpperCase());
var s2 = b.surname.toUpperCase().indexOf(queryString.toUpperCase());
return (s1 > -1 && s1 > s2);
});
Fiddle with full code
At least it worked with both examples you provided, but I'm not sure if it is all you need.

Categories

Resources