Add new value into json - javascript

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

Related

JavaScript: Comparing two objects

I want to compare two objects to make a new object.
original = [
{id: "A1", name: "Nick", age: 20, country: 'JP', code: 'PHP'}
]
edited = [
{name: "Mike", age: 30, country: 'US'},
{id: "A1", name: "Nick", age: 25, country: 'US', code: 'PHP'}
]
Compare two objects ('original' and 'edited')
If 'id' is set, compare the same ids' data, and take the data from 'edited', and get ONLY the 'id' and the data that is edited.
If 'id' is not set keep the whole data
The final object I want is like below;
final = [
{name: "Mike", age: 30, country: 'US'},
{id: "A1", age: 25, country: 'US'}
]
I've been trying this using filter, but I can't get desired result...
Try with Array#reduce .
Updated with all key pair match
Validate the edited array id value is available in original array using Array#map and indexOf function
If not push entire object to new array
First recreate the original array to object format like {key:[value]}
Then match each key value pair match or not with forEach inside the reduce function
var original = [{id: "A1", name: "Nick", age: 20, country: 'JP'}];
var edited = [{name: "Mike", age: 30, country: 'US'},{id: "A1", name: "Nick", age: 25, country: 'US'}];
var ids_org = Object.keys(original[0]).reduce((a,b,c)=> (a[b]=original.map(a=> a[b]),a),{});
var res = edited.reduce((a, b) => {
if (b.id) {
Object.keys(b).forEach(i=>{
if(ids_org[i].indexOf(b[i]) > -1 && i != 'id')
delete b[i];
})
a.push(b);
} else {
a.push(b);
}
return a;
}, []);
console.log(res)
use de structuring to extract out id from the object.
use lodash isEqual method to compare and later add back the id to the object.

Check if same object exists in an array - Javascript

I have an array of objects as follows
[{name: "jack", age: 10}, {name: "john", age: 15}]
Consider that i have an object
{name: "jack", age: 10}
Now i need to check if this object exist in the array. If all the properties(name, age) of the object matches, then display an alert on the page.
How to accomplish this using pure javascript?
Use Array.some, Array.every and Object.entries
A match will be counted if
There are equal number of keys
There is a match for every key/value pair
var arr = [{name: "jack", age: 10}, {name: "john", age: 15}];
var input = {name: "jack", age: 10};
var result = arr.some((o) => Object.entries(input).every(([k,v]) => o[k] === v) && Object.keys(input).length === Object.keys(o).length);
console.log(result);
Try this:
var data = [{name: "jack", age: 10}, {name: "john", age: 15}];
var input = {name: "jack", age: 10};
for(var i=0;i<data.length;i++)
{
if(data[i].name==input.name && data[i].age == input.age)
{
alert('matched');
break;
}
}
This may be a bad performing method, but it would cover nested object cases with ease. Also this is only suited if ALL key/value pairs must match and that the key/value pairs were defined in the same order.
let c = [{name: "jack", age: 10}, {name: "john", age: 15}],
s = {name: "jack", age: 10};
console.log(c.filter(e => JSON.stringify(s) === JSON.stringify(e)));
You can try this if you don't want to check for index of object inside array object
var obj = [{name: "jack", age: 10}, {name: "john", age: 15}];
var checkObj = {name: "john", age: 15};
if(JSON.stringify(obj).indexOf(JSON.stringify(checkObj)) >= 0){
console.log("Object Available");
}else{
console.log("Object Not Available");
}

Iterating and filtering with ES6/lodash

We have an array of objects like:
const persons = [{
name: "john",
age: 23
}, {
name: "lisa",
age: 43
}, {
name: "jim",
age: 101
}, {
name: "bob",
age: 67
}];
And an array of a attribute values of the objects in object
const names = ["lisa", "bob"]
How can we find persons with name in the names array using es6, like:
const filteredPersons = [{
name: "lisa",
age: 43
}, {
name: "bob",
age: 67
}];
ES6
Use filter function with predicate and in it check the existence of the name in the names array.
const persons = [
{name: "john", age:23},
{name: "lisa", age:43},
{name: "jim", age:101},
{name: "bob", age:67}
];
const names = ["lisa", "bob"];
const filtered = persons.filter(person => names.includes(person.name));
console.log(filtered);
You can use filter() and inlcudes() to get required result.
DEMO
const persons = [{
name: "john",
age: 23
}, {
name: "lisa",
age: 43
}, {
name: "jim",
age: 101
}, {
name: "bob",
age: 67
}];
const names = ["lisa", "bob"];
console.log(persons.filter(({
name
}) => names.includes(name)))
.as-console-wrapper { max-height: 100% !important; top: 0; }
I would suggest to use indexOf as includes does not work in IE browser. Also, using {name} works as Destructuring assignment that will hold the value of name property of the object.
const persons = [{
name: "john",
age: 23
}, {
name: "lisa",
age: 43
}, {
name: "jim",
age: 101
}, {
name: "bob",
age: 67
}];
const names = ["lisa", "bob"];
console.log(persons.filter(({name}) => names.indexOf(name) !== -1))
lodash
You can try following
const persons = [{name: "john", age: 23},
{name: "lisa",age: 43},
{name: "jim", age: 101},
{name: "bob",age: 67}];
const names = ["lisa", "bob"]
const filteredPersons = _.filter(persons, function(person) {
return _.indexOf(names, person.name) !== -1;
});
console.log(filteredPersons);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
In case you want to perform it in n complexity, here is a way to do it:
Create a map with key as person's name and value as person's object.
Map the criteria array and extract the person objects from the map create in step 1.
Here is a working demo:
const persons = [{
name: "john",
age: 23
}, {
name: "lisa",
age: 43
}, {
name: "jim",
age: 101
}, {
name: "bob",
age: 67
}];
const names = ["lisa", "bob"];
const map = persons.reduce((acc, item) => {
acc[item.name] = item;
return acc;
}, {});
const result = names.map(name => map[name]);
console.log(result);
Note: This solution assumes that only unique person names are in the source array. It needs to be tweaked to handle duplicates.
See Closures, Set, and Array.prototype.filter() for more info.
// Input.
const persons = [{name: "john",age: 23}, {name: "lisa",age: 43}, {name: "jim",age: 101}, {name: "bob",age: 67}]
const names = ["lisa", "bob"]
// Filter.
const filter = (A, B) => (s => A.filter(x => s.has(x.name)))(new Set(B))
// Output.
const output = filter(persons, names)
// Proof.
console.log(output)

Merge Array of Objects

I need to merge arrays of objects in browserside javascript like this:
[
{name: "john", age: 10},
{name: "doe", age: 14}
]
--> new data arrives
[
{name: "pete", age: 88},
{name: "larry", age: 42}
]
should become
[
{name: "john", age: 10},
{name: "doe", age: 14},
{name: "pete", age: 88},
{name: "larry", age: 42}
]
Well thats simplified the arrays will contain hundreds of larger objects. Therefore I need a performant solution.
Thanks in advance yours skeec
It seems you can just use .push() or .concat() to combine the two arrays. It does not matter what is in the arrays as the array operators just work on the elements of the array abstractly without knowing what's in them.
Here's a solution that adds the new array onto the existing one:
var data = [
{name: "john", age: 10},
{name: "doe", age: 14}
];
var newInfo = [
{name: "pete", age: 88},
{name: "larry", age: 42}
]
data = data.concat(newInfo);
Or, if you really want to keep the original array (not create a new one), you can add the new array onto the end of the original array like this:
data.push.apply(data, newInfo);
Assuming you don't need anything other than just concatenating the 2 arrays, it's supremely simple, since arrays have a method for concatenation already.
var arr1 = [
{name: "pete", age: 88},
{name: "larry", age: 42}
];
var arr2 = [
{name: "pete", age: 88},
{name: "larry", age: 42}
];
var concatArr = arr1.concat(arr2);
MDN Page on Array.prototype.concat
var arr3 = [];
for(var i in arr1){
var shared = false;
for (var j in arr2)
if (arr2[j].name == arr1[i].name) {
shared = true;
break;
}
if(!shared) arr3.push(arr1[i])
}
arr3 = arr3.concat(arr2);
You can use loadash for that:
Something like this:
var array = [1];
var other = _.concat(array, 2, [3], [[4]]);
console.log(other);
// → [1, 2, 3, [4]]
console.log(array);
// → [1]
Or for Json you can use extend like this:
lodash.extend({}, mergeInto, toMerge)

Dynamically insert object into existing object

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;

Categories

Resources