I want to Update array of objects by another array of objects.
I have 2 array of objects like this:
const array = [
{id:'a',html:'',user:''},
{id:'b',html:'',user:''},
{id:'c',html:'',user:''},
];
const array_two = [
{id:'a',html:'',user:''},
{id:'b',html:'',user:''},
{id:'c',html:'',user:''},
{id:'d',html:'<p>Hello World</p>',user:'TEST USER'},
{id:'e',html:'<p>Hello World TWO</p>',user:'TEST USER TWO'},
];
and I want updateenter code here array by anotherArray
So my desired output is:
[
{id:'a',html:'<p>Hello World</p>',user:'TEST USER'},
{id:'b',html:'<p>Hello World TWO</p>',user:'TEST USER TWO'},
{id:'c',html:'',user:''},
];
Assuming (unlike your example) that you want objects with matching ids to update, here's how I would implement this:
Build an object byId mapping ids to corresponding object.
Loop through the updates and apply Object.assign to update the objects in-place, using byId to know which object to update.
const byId = {};
array.forEach((obj) => byId[obj.id] = obj);
array_two.forEach((obj) => {
if (!Object.hasOwnProperty(byId, obj.id)) {
// Create new object if id doesn't already exist.
byId[obj.id] = obj;
array.push(obj);
} else {
// Update existing object.
Object.assign(byId[obj.id], obj);
}
});
Related
I have duplicate values looks like as shown in below figure
I have used below code but its only giving the names like as ashare1 guideline2and i am looking for id as well.
please find the below code currently i have used
const optionMap0 = [
...new Set(libraryEquipment.map(e => e.equipmentSource.name)),
{
id: '1d037be564c548eebe71db4e45e26cf7',
name: 'None',
},
];
Could any one please suggest any idea on how to get distinct values from the above array of objects.
many thanks in advance
You can convert it to an object, with the key as the name, and the value as the object itself, and then use Object.values() to get the objects.
const obj = {};
libraryEquipment.forEach(e => obj[e.equipmentSource.name] = e.equipmentSource);
const optionMap0 = Object.values(obj);
Unlike set, if you have more than one object with the same name, it will keep the last one. You can check before adding the object so it will use the first object with the same name, like so:
const obj = {};
libraryEquipment.forEach(e => {
if (!obj[e.equipmentSource.name])
obj[e.equipmentSource.name] = e.equipmentSource'
});
const optionMap0 = Object.values(obj);
I was trying one simple piece of code in which an array of objects are present and each object is having another array of products(with duplicate values).
I wanted to combine all the products array together without any duplicates.
Already reached half of iteration process but not able to remove duplicates, is there any way to iterate the values (as it is itself having key value as object 1 and its data..)
please suggest any other optimized way if possible. I'm new to JavaScript so pardon any silly mistakes made
Thanks in advance.
You can do it using concat, Set and Array.from:
const object1 = { products: ['1', '2', '3'] }
const object2 = { products: ['1', '2', '3', '4'] }
const object3 = { products: ['5'] }
// Merge all the products in one Array
const products = object1.products
.concat(object2.products)
.concat(object3.products);
// Create a Set, with the unique products
const set = new Set(products);
// Convert the Set to an Array
const uniqueProducts = Array.from(set);
console.log(uniqueProducts)
To remove duplicates you can use Set, it keeps all items unique, then you can cast it to Array.
Array.from(new Set(array))
there are many ways to achieve this:
you can use filter to remove duplicate elements:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
by reading in value, its index and array in filter function
a quick search link: https://codeburst.io/javascript-array-distinct-5edc93501dc4
you can always write a method for merge which would be good in terms of error handling, corner case checks, so that above action dont result into error,
example:
function MergeUniqueProductFromDictToArry(fromDict, productKey, toArray) {
//check if for the array in which we need to merge
if(!toArray) {
toArray = [];
}
//check for validity
if(!fromDict || !productKey || !fromDict[productKey] || fromDict[productKey].length == 0) {
return toArray;
}
for(var ix in fromDict[productKey]) {
//check if product already exist
if(toArray.indexOf(fromDict[productKey][ix]) === -1) {
toArray.push(fromDict[productKey][ix]);
}
}
return toArray;
}
var object1 = {products: ["p1", "p2", "p1"]};
var object2 = {products: ["p3", "p2"]};
var object3 = {products: ["p4", "p2"]};
var uniqueProducts = MergeUniqueProductFromDictToArry(object1, "products", null);
uniqueProducts = MergeUniqueProductFromDictToArry(object2, "products", uniqueProducts);
uniqueProducts = MergeUniqueProductFromDictToArry(object3, "products", uniqueProducts);
console.log(uniqueProducts);
I need to add key:value into an object.
var a = {}
a['first'] = [a,bunch,of,stuff]
a['eight'] = [another,bunch,of,stuff]
a['two'] = [more,stuff]
but now variable 'a' contains
{eight: [a,bunch,of,stuff],first: [another,bunch,of,stuff],two: [more,stuff]}
while what I wanted was
{first: [another,bunch,of,stuff], eight: [a,bunch,of,stuff],two:[more,stuff]}
I'm guessing the order is based on the alphabetical order of the keys. This is a problem, because I want to display the data into hbs using {#each model as |key value|} in the same order as I wanted it.
in most languages lists have order where objects and sets do not. objects are key value and have no order.
in js arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays
this basically means you can place data anywhere in array, and it will be in order in the array
var idx = [];
idx[0] = 'hello';
idx[999] = 'world';
so what i believe you're looking for is
var listOfThings = [];
listOfThings.push({ 'first': [ 'things' ] })
listOfThings.push({ 'eight': [ 'stuff' ] })
listOfThings.push({ 'two': [ 'more'. 'things' ] })
then you can loop over accessing the key and value for each object.
Example you have an object, which is already have 2 key pairs, a1 & b2. Then you would like to add k3, you can use this method :
let objData = [{"a1":10,"b2":20},{"b2":11,"a1":23}]
Object.keys(objData).map(
function (object) {
// add k3
objData[object]["k3"] = "foo"
})
Then if you want to sort the keys alphabetically, use this method :
function orderKeyAlfAsc(obj) {
let data = []
for (var i in obj)
data.push(Object.keys(obj[i]).sort().reduce((r, k) => (r[k] = obj[i][k], r), {}))
return data
}
let orderedData = orderKeyAlfAsc(objData)
How to create new array from slicing the existing array by it's key?
for example my input is :
var array = [{"one":"1"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},
{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},
{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},
{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},
{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005"} ];
my output should be :
var outPutArray = [
{"one" : ["1","01","001","0001","00001"]},
{"two":["2","02","002","0002","00002"]},
{"three":["3","03","003","0003","00003"]},
{"four":["4","04","004","0004","00004"]},
{"five":["5","05","005","0005","00005"]}
]
is there any short and easy way to achieve this in javascript?
You can first create array and then use forEach() loop to add to that array and use thisArg param to check if object with same key already exists.
var array = [{"one":"1","abc":"xyz"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005","abc":"xya"} ];
var result = [];
array.forEach(function(e) {
var that = this;
Object.keys(e).forEach(function(key) {
if(!that[key]) that[key] = {[key]: []}, result.push(that[key])
that[key][key].push(e[key])
})
}, {})
console.log(result);
var outputArray=[array.reduce((obj,el)=>(Object.keys(el).forEach(key=>(obj[key]=obj[key]||[]).push(el[key])),obj),{})];
Reduce the Array to an Object,trough putting each Arrays object key to the Object as an Array that contains the value.
http://jsbin.com/leluyaseso/edit?console
Let's say I have an array of JSON objects such as below:
{
title: 'foo',
alias: 'bam',
innerArr: [{
name:'foo',
id:'123',
options: [{id:3,title:'boo',values:[{id:5,name:'Boo'}] }]
}]
}
Is there any library or shorthand method that doesn't involve writing nested for loops that will iterate over a collection of such objects and create a new array, but only with the properties I want projected/selected. So, say I want a copy of this array, but don't want the property title and the nested options[{}] array in the target array. So this new array will have all the same data, but each member of the array will now not have those two objects. Something I can overload like so perhaps var newarr = method({}, sourceArray, {title, options });
Just create a clone object (or you could work on initial object) and delete what you want, e.g:
var newObj = JSON.parse(JSON.stringify(o));
delete newObj.title;
newObj.innerArr.forEach(function(_o, i){delete _o.options});
console.log(newObj);
If you have to deal with specific nested objects as Date, use jQuery extend to clone object.
var newObj = $.extend({}, oldObject);
Let's say I have an array of JSON objects
For an array of object:
var newArr = JSON.parse(JSON.stringify(arr));
newArr.forEach(function (_o, i) {
delete _o.title;
_o.innerArr.forEach(function (__o, i) {
delete __o.options
});
});
console.log(newArr);
-jsFiddle-
EDIT: now i guess some library as prototypejs would have some handful methods but i don't know this library.