How to populate an array of objects dynamically? - javascript

let products = [
{
name: "a",
inventory: 1
},
{
name: "b",
inventory: 2
},
{
name: "c",
inventory: 3
}
];
How can I go about creating these objects in an array like this dynamically ?
Here is what I have been trying to do.
choicesHolder = [{name: '', inventory: ''}];
for(i; element.length<0; i--) {
choicesHolder.push({"name": element.value, "inventory": element.selected});
}
element holds the data from the JSON.

You can use the map method.
MDN docs about map
const choicesHolder = arrayOfElement.map(element => {
return {
name: element.value,
inventory: element.selected
}
})

Try this:
let res = [];
let char = 'a'
for (let i = 0; i < 4; i++) {
res.push({ "name": char, "inventory": i + 1 });
char = String.fromCharCode(char.charCodeAt(0) + 1) // 'B'
}
console.log(res)

Related

Find the unique id of the item and group its value in array using reduce method?

Please help me to find the expected output from the given scenario
input array:
const items = [
{ id: 1, name: "a" },
{ id: 2, name: "b" },
{ id: 3, name: "c" },
{ id: 1, name: "d" },
{ id: 3, name: "f" },
{ id: 1, name: "a" },
{ id: 3, name: "c" },
]
expected output:
[{ id: 1, names: ['a', 'd']},
{ id: 2, names: ['b']},
{ id: 3, names: ['c', 'f']}]
You can create a new array, loop through your main array and check if there is an object with the current id in the new array and update it or create a new object accordingly.
Like this:
let newItems = [];
items.forEach(item => {
let index = newItems.findIndex(el => el.id == item.id);
if (index > -1) {
if (newItems[index]['names'].indexOf(item.name) === -1) {
return newItems[index]['names'].push(item.name)
}
} else {
newItems.push({id: item.id, names: [item.name]});
}
});
With reduce method:
const newArr = items.reduce((pv, cv) => {
let index = pv.findIndex(el => el.id == cv.id);
if (index > -1) {
if (pv[index]['names'].indexOf(cv.name) === -1) {
pv[index]['names'].push(cv.name)
}
} else {
pv.push({id: cv.id, names: [cv.name]});
}
return pv;
}, []);
pv is previous value which is the new array, cv is current value which is each object in items array. Initial value of newArr is []
You can use spread operator and retrieve the values of the duplicate key and push it in the new array of objects.
Thanks & Regards

remove the second occurrence of array object with same name

I have this array (java script array of objects)
users=[{name:'arrow',age:50,id:444}
{name:'bow',age:66,id:884}
{name:'arrow',age:30,id:99},
{name:'apple',age:50,id:999}
{name:'bow',age:50,id:9669}]
I want to remove second occurrence of same name , in this case , I want to remove {name:'arrow',age:30,id:99} and {name:'bow',age:50,id:9669} and retain first occurrences{name:'arrow',age:50,id:444} and {name:'bow',age:66,id:884}
Resulting array should be :
users= [{name:'arrow',age:50,id:444}
{name:'bow',age:66,id:884},
{name:'apple',age:50,id:999}]
const users = [
{ name: 'arrow', age: 50, id: 444 },
{ name: 'bow', age: 66, id: 884 },
{ name: 'arrow', age: 30, id: 99 },
{ name: 'apple', age: 50, id: 999 },
{ name: 'bow', age: 50, id: 9669 }
]
const uniqueUsers = users.reduce((acc, user) => {
if (!acc.find(u => u.name === user.name)) {
acc.push(user)
}
return acc
}, [])
I'd go with the approach of array.filter:
function removeDuplicateKeyFromArray(arrayOfObjects,keyName){
keyHolder = {}
arrayOfObjects.filter((obj)=>{
if(keyHolder[obj.keyName]){
return false
}
keyHolder[obj.keyName] = 1 //or true
return true
})
}
I would create 2 for-loops, to filter out any duplicates.
here's my code:
let users = [{name:'arrow',age:50,id:444},
{name:'bow',age:66,id:884},
{name:'arrow',age:30,id:99},
{name:'apple',age: 50,id: 990},
{name:'bow',age: 50,id: 9669}]
for (let i = 0; i < users.length; i++) {
for(let x = 0; i < users.length; i++) {
if(users[i].name == users[x].name) {
users.splice(users[x], 1)
}
}
}

How to get index of a 2d array of 2 similar structure ones with same value

Sorry the title may not present well.
I got two 2d arrays with similar structure.
array A:
arrayA[0]['account_name'] = 'a0';
arrayA[1]['account_name'] = 'a1';
arrayA[2]['account_name'] = 'a2';
And array B:
arrayB[0]['account_name'] = 'a1';
arrayB[1]['account_name'] = 'b0';
arrayB[2]['account_name'] = 'c0';
arrayB[3]['account_name'] = 'a0';
arrayB[4]['account_name'] = 'd3';
arrayB[5]['account_name'] = 'e8';
arrayB[6]['account_name'] = 'a3';
arrayB[7]['account_name'] = 'b4';
arrayB[8]['account_name'] = 'b1';
Now I know arrayA[0]['account_name'] equals to "a0", how can I search efficiently to check if it also exists in array B / know its position in array B? And I would like to loop for all values in array A.
const a = [
{ name: 'a0' },
{ name: 'a1' },
{ name: 'b2' }
];
const b = [
{ name: 'a0' },
{ name: 'a1' },
{ name: 'a2' },
{ name: 'b0' },
{ name: 'b1' },
{ name: 'b2' }
];
a.forEach((aa, i) => {
let found;
b.forEach((bb, j) => {
if(aa.name === bb.name) {
found = {
index: j,
value: aa.name
};
return true;
}
});
console.log(found);
});

Get index of parent object in nested object array

I have this array:
[
{
elements: [
{ id: '123', field: 'value' }
{ id: '456', field: 'value' }
]
}
{
elements: [
{ id: '789', field: 'value' }
]
}
]
Now I need to get the index of the first level object searching by an id:
searching for id = '456' should give me 0, id = '789' should give me 1
You can do this with findIndex() and some()
var arr = [{
elements: [{
id: '123',
field: 'value'
}, {
id: '456',
field: 'value'
}]
}, {
elements: [{
id: '789',
field: 'value'
}]
}]
var i = arr.findIndex(function(o) {
return o.elements.some(function(e) {
return e.id == 456;
})
})
console.log(i)
Get the feeling that something could be fixed to rethink this. But who knows.
456 should give u id 1 and so should 789 aswell.
var mapped = whatEverObject[0].elements.map(function(obj){ //0 = first
return obj.id;
})
console.log(mapped.indexOf(456)) // will give you 1 since id:123 is id 0 in the first elements array.
You can make a lookup table. It will be much faster if you do several lookups.
Live Example
var table = makeNestedLookupTable(example);
// table[789] would be 1 if the array in the question were "example"
function makeNestedLookupTable(data) {
return data.reduce(function(lookup, obj, topIndex) {
return obj.elements.reduce(function(lookup, element) {
lookup[element.id] = topIndex;
return lookup;
}, lookup);
}, {});
}
You can use this function getIndex which loops through the array and matches the id of the element with the given id and returns the index.This solution will work in all browsers.
var arr = [
{
elements: [
{ id: '123', field: 'value' }
{ id: '456', field: 'value' }
]
}
{
elements: [
{ id: '789', field: 'value' }
]
}
];
function getIndex(arr, id) {
var i, ii, len, elemlen;
for (i = 0, len = arr.length; i < len; i++) {
elements = arr[i].elements;
for (ii = 0, elemlen = elements.length; ii < elemlen; ii++) {
if (elements[ii].id === id) {
return i;
}
}
}
}
var index = getIndex(arr, '456');
Here is a generic code where you can send an array and the lookup attribute:
function giveLevel(a,attr){
for(var i=0;i<a.length;i++){
var o = a[i];
var tmp = JSON.stringify(o);
if(tmp.indexOf(attr)!==-1){
return i;
}
}
}
var a = [{elements: [
{ id: '123', field: 'value' },
{ id: '456', field: 'value' }
]
},
{
elements: [
{ id: '789', field: 'value' }
]
}
];
giveLevel(a,'"id":"789"'); // returns 1

array with objects transformation

I have an array with objects smth like this:
arr = [
{name: 'Igor', id: 1,....},
{name: 'Anton', id: 1,.... },
{name: 'Igor', id: 2,.... },
{name: 'Peter', id: 2,.... },
{name: 'Igor', id: 2,.... }
]
I need to get new array like:
arrId = [
{ id: 1, names: 'Igor, Anton' },
{ id: 2, names: 'Igor, Peter' }
]
can't think of good solution
In this example I use map and reduce.
function rearrange(arr) {
// use `reduce` to build an object using the ids as keys
// this allows us to place all the names with the same id together
// note we pass in an empty object to act as our initial p argument.
var out = arr.reduce(function (p, c) {
var key = c.id, name = c.name;
// if the key doesn't exist create it and set its value
// to an empty array
p[key] = p[key] || [];
// add the name to the array if it doesn't already exist
if (p[key].indexOf(name) === -1) p[key].push(name);
return p;
}, {});
// use `map` to return an array of objects
return Object.keys(out).map(function (el) {
// make sure we use an integer for the id, and
// join the array to get the appropriate output
return { id: +el, names: out[el].join(', ') };
});
}
rearrange(arr);
DEMO
OUTPUT
[
{
"id": 1,
"names": "Igor, Anton"
},
{
"id": 2,
"names": "Igor, Peter"
}
]
You can use reduce function
arr = [
{name: 'Igor', id: 1},
{name: 'Anton', id: 1 },
{name: 'Igor', id: 2 },
{name: 'Peter', id: 2 },
{name: 'Igor', id: 2 }
]
//first group needed fields from items by id
var result = arr.reduce(function(acc,cur){
if(!acc.map[cur.id]) {
acc.map[cur.id] = {id:cur.id, names:{}};
acc.result.push(acc.map[cur.id]);
}
acc.map[cur.id].names[cur.name]=true;
return acc;
},{map:{},result:[]})
//do addtional transfrom from map object with names, to string separated by comma
.result.map(function(el){
return {id:el.id, names: Object.keys(el.names).join(', ')};
});
console.log(result);
document.body.innerHTML = JSON.stringify(result,null, 2);
var arrId = [];
var arrKey = {};
for( var counter = 0; counter < arr.length; counter++)
{
var arrObj = arr[ counter ];
if ( !arrKey[ arrObj[ "id" ] ] )
{
arrKey[ arrObj[ "id" ] ] = [];
}
arrKey[ arrObj[ "id" ] ].push( arrObj[ "name" ] );
}
for ( var id in arrKey )
{
arrId.push( [ "id": id, names : arrKey[ id ].join( "," ) ] );
}
console.log(arrId );

Categories

Resources