JS arrays: how to compare two and create third - javascript

It's my first post here :-)
Please, Can you a advice on this:
I have an object and an Array:
activeItems = {
itemId: ["itemid1", "itemid2", "itemid3", "itemid4", "itemid5", "itemid6", "itemid7", "itemid8", "itemid9", "itemid10"],
price: ["10.50", "22.10", "13.40", "11", "1100", "500", "100", "400", "500", "20"]
};
selectItems = ["itemid3", "itemid8", "itemid9"];
In the activeItems object price[0] represents the price for itemId[0].
All the prices are in correct order to represent prices for all item ids.
Now, I would like to create a new object with prices for the selecteItems array.
It should look like this:
newObject = {
itemId: ["itemid3","itemid8","itemid9"],
price: ["13.40", "400", "500"]
};
Basically, I'm looking for a formula that creates new object for selectedItems out of activeItems and adds prices arrays for them.
Thank you in advance!

Use a forEach loop and get the index of items from activeItems.itemId which can be used to get the corresponding price value from activeItems.price.
var activeItems = {
itemId: ["itemid1", "itemid2", "itemid3", "itemid4", "itemid5", "itemid6", "itemid7", "itemid8", "itemid9", "itemid10"],
price: ["10.50","22.10","13.40","11","1100","500","100","400","500","20"]
};
var selectItems = ["itemid3","itemid8","itemid9"];
var itemId = [];
var price = [];
selectItems.forEach(function(item){
var index = activeItems.itemId.indexOf(item);
itemId.push(item);
price.push(activeItems.price[index]);
});
var newObject = {
itemId: itemId,
price : price
};
console.log(newObject);

Maybe this is what you need: Key value arrays:
var myArray = {"itemid3": "13.40", "itemid8": "400", "itemid9": "500"};
And you add new items like this:
myArray = [];
myArray.itemid15 = "300";

Use the array reduce function
var activeItems = {
itemId: ["itemid1", "itemid2", "itemid3", "itemid4", "itemid5", "itemid6", "itemid7", "itemid8", "itemid9", "itemid10"],
price: ["10.50", "22.10", "13.40", "11", "1100", "500", "100", "400", "500", "20"]
};
var selectItems = ["itemid3", "itemid8", "itemid9"];
var newObject = selectItems.reduce(function(acc, curr, index) {
// acc is the object passes as an argument
// curr is current element
// in this case curr will be "itemid3", "itemid8", "itemid9" ..so on
acc.itemId.push(curr);
// in next step get the index of the itemId3 etc from the original array
// use this index to get the value from activeItems .price
acc.price.push(activeItems.price[activeItems.itemId.indexOf(curr)])
return acc;
}, {
itemId: [],
price: []
});
console.log(newObject)

Related

Convert a one dimensional array into an array of objects with Javascript

I've flattened an array like this: let playerPool = [...new Set(array.flat(1))];
Which has an output like this: ["Howard Bell", "Matt Blair", "Dave Custer"]
How can I turn this into an array of objects? I want to update the above so the format is like this:
[ {Name: "Howard Bell", Count: "0"}, {Name: "Matt Blair", Count: "0"}, {Name: "Dave Custer", Count: "0"} ]
I was trying to set this up by looping through the playerPool array but I get the following error: TypeError: Cannot set property 'Name' of undefined
let playerPool = [...new Set(array.flat(1))];
let playerObjects = [];
for(let i = 0; i < playerPool.length; i++) {
playerObjects[i].Name = playerPool[i];
playerObjects[i].Count = 0;
}
My goal is to be able to reference each property individually like this playerObjects[0].Count so I can later update the count value.
You forgot to create the object to which you want to assign the properties.
But you can do it more functional-style with map:
let playerPool = ["Howard Bell", "Matt Blair", "Dave Custer"];
let result = playerPool.map(name => ({name, count:0}));
console.log(result);
NB: if possible choose camelCase for your property names. There is a common practice to reserve PascalCase for constructor names ("classes").
You can try something like this,
let array1 = ["Howard Bell", "Matt Blair", "Dave Custer"];
let array2 = [];
array1.forEach(el => {
array2.push({Name: el, count: 0});
});
console.log(array2);

Add key value to all objects in array from another with JavaScript

I wanted to add a key:value parameter to all the objects in an array from another array
eg:
var arrOfObj = [{id: 001, date:'22/05/2020', Actor:'jane'},
{id: 002, date:'02/03/2020', Actor:'alice'},
{id: 003, date:'11/06/2020', Actor:'jean'},
{id: 004, date:'20/01/2020', Actor:'yann'}];
var arrayScore = [44,2,3,5];
I want add for every objects a key:value parameter from arrayScore, like :
var arrOfObj = [{id: 001, date:'22/05/2020', Actor:'jane', score:44},
{id: 002, date:'02/03/2020', Actor:'alice', score:2},
{id: 003, date:'11/06/2020', Actor:'jean', score:3},
{id: 004, date:'20/01/2020', Actor:'yann', score:5}];
I tried this code:
var result = arrOfObj.map(function(el) {
var o = Object.assign({}, el);
o.score = arrayScore;
return o;
});
console.log(result);
but arrOfObj add all values from arrayScore for every object!!
How can I change this please??
Thank you for your HELP!
You can use Array.map to create the new array including the user scores, I would also take note of TJCrowders's point about the Ids.
var arrOfObj = [{id: 1, date:'22/05/2020', Actor:'jane'},
{id: 2, date:'02/03/2020', Actor:'alice'},
{id: 3, date:'11/06/2020', Actor:'jean'},
{id: 4, date:'20/01/2020', Actor:'yann'}];
var arrayScore = [44,2,3,5];
const result = arrOfObj.map((el, index) => ({...el, score: arrayScore[index] }));
console.log("Result with scores:", result);
Since you do not need a new array of objects, but only need to add the properties to the objects in the array, you can use the array method forEach instead of map.
If we pass two parameters to the callback provided to forEach, the second parameter will receive the index of the array element we are iterating over. This allows us to assign the corresponding value from the arrayScore array.
This should work
arrOfObj.forEach((o, i) => {
o.score = arrayScore[i];
});
Cheers!

acessing new object from Object.keys and forEach method javascript

I'm trying to create a new object (newobj) with new keys and props from a poorly structured existing array of object (arrays?) ex.
[{"product":["1009", "name", "price", "image", "description"]},
{"product":["1004", "name2", "price2", "image2", "description2"]}]
I'm getting result I want but newobj does not update outside of the scope of the forEach method (more than 1 result). My question is what am I not getting ? Is forEach incorrect method with this type obj?
var newobj = {};
Object.keys(oldobj).forEach(function(prop) {
newobj["id"] = Number(oldobj[prop]["product"][0]),
newobj["name"] = oldobj[prop]["product"][1],
newobj["price"] = Number(oldobj[prop]["product"][3]),
newobj["image"] = "url" + oldobj[prop]["product"][0] + ".jpg",
newobj["description"] = oldobj[prop]["product"][2];
// this works
// console.log(JSON.stringify(newobj));
});
// this only updated with one
app.locals.newobj = newobj;
I've also tried mapping (w/ underscore) but I have the same result, I can't access outside scope.
_.each(mappedobj, function(prop) {
_.each(prop["product"][0], function(vals){
newobj["id"] = Number(prop["product"][0]);
console.log(JSON.stringify(newobj));
});
});
If you want all the values from the old object, you need to make newobj an array of objects. You can use .map() to do this transformation.
Object and array destructuring is a convenient way to avoid all those hard-coded indexes. And by naming the parameter variables properly, you can use object literal shorthand to create the resulting objects more easily.
var oldobj = [{
"product": ["1009", "name", "price", "image", "description"]
},
{
"product": ["1004", "name2", "price2", "image2", "description2"]
}
];
var newobj = oldobj.map(({product: [id, name, price, url, description]}) =>
({id: Number(id), name, price: Number(price), url: `url${url}.jpg`, description})
);
console.log(newobj);
Try this
let newObject = _.map(oldObject, (item) => {
return {
id: item.product[0],
name: item.product[1],
price: item.product[2],
image: item.product[3],
description: item.product[4]
};
});
If you want to convert an array of poorly structured object to an array of well structured ones, you can use Array.prototype.map from VanillaJS:
const data = [
{"product": ["1009", "name", "120", "image", "description"]},
{"product": ["1004", "name2", "250", "image2", "description2"]},
{"product": ["1012", "name3", "85", "image3", "description3"]}
];
const products = data.map(({ product }) => {
const [id, name, price, image, description] = product;
return {
id: Number(id),
name,
price: Number(price),
image: `url${image}.jpg`,
description
};
});
console.log(products);

Delete objects from array of objects

Object {Results:Array[3]}
Results:Array[3]
[0-2]
0:Object
id=1
name: "Rick"
upper:"0.67"
1:Object
id=2
name:'david'
upper:"0.46"
2:Object
id=3
name:'ashley'
upper:null
I have this array of objects as shown above. and a variable named delete_id
delete_id = 1,2
So this indicates objects with id 1 and 2. It should delete the objects in the array of objects and give the final result as follows:
Object {Results:Array[1]}
Results:Array[3]
[0]
0:Object
id=3
name:'ashley'
upper:null
Can someone let me know how to achieve this. I tried to use this below function. It only deletes the first value in variale delete_id. i.e. id with 1 is deleted. similary if we have delete_id = 2,3 then it only deletes 2. I want to delete 2 and 3 both...
function removeID(delete_id) {
tabledata = tabledata.filter(function (obj) {
return delete_id.indexOf(obj.id);
});
You can use .split() and .map() to transform your delete_id string into an array of numeric IDs. Then, you can use .filter() to do the cleanup.
var players = [
{
id: 1,
name: "Rick",
upper: "0.67"
},{
id: 2,
name: "david",
upper: "0.46"
},{
id: 3,
name: "ashley",
upper: null
}
];
var delete_id = "1,2";
var exclude = delete_id.split(',').map(Number);
players = players.filter(function(player) {
return exclude.indexOf(player.id) == -1;
});
console.log(players);
function findObj(array,value,key) {
var result = array.filter(function (obj) {
if (obj[key] === value || obj[key] == value)
return obj;
});
return result;
};
First find the object from the
array(tabledata),value=1(delete_id),key=the key in json(id)
var selectedObj=findObj(tabledata,delete_id,'id');
get index of that object in the array
var index=tabledata.indexOf(selectedObj[0]);
delete its index
tabledata.splice(index,1);
The code runs if you change the removeID code to see if the index is equal to -1
function removeID(delete_id) {
tabledata = tabledata.filter(function(obj) {
return delete_id.indexOf(obj.id)===-1; //added === -1 here
});
}
var tabledata = [{
id: 1,
name: "Rick",
upper: "0.67"
}, {
id: 2,
name: 'david',
upper: "0.46"
}, {
id: 3,
name: 'ashley',
upper: null
}];
var ids = [1,2]; //defined it as an array (not sure if you did)
removeID(ids);
console.log(tabledata);
I assume that delete_id is an integer array. In that case you can filter to exclude provided ids with code below.
It'll check if obj.id is not in delete_id, then obj will be included in a new filtered array. Also it will leave tabledata intact.
var filtered = tabledata.filter(function(obj) {
return !(obj.id in delete_id)
})

Strip key values out of object array with javascript

I have an array with this data in it:
[
{
user1post2: {
ad:"Car", ac:39500, af:"4", ah:"klgjoirt3904d", ab:"Acura",
ae:"2013 ACURA MDX 3.5L V6 AWD 6AT (294 HP)", ag:"Mint", aa:"Option2"
},
user1post1: {
ad:"Truck", ac:6799, af:"3", ah:"ldkfldfjljKey", ab:"GMC",
ae:"1/2 Ton with plow", ag:"Mint Looks", aa:"Option1"
}
}
]
I need to strip out user1post2 and user1post1.
I've tried using something like this, but it doesn't work:
var valu2 = values; //put current array into new variable `valu2`
console.log(valu2.toSource()); //Log to console to verify variable
var finalData = []; //Create new array
for (var name2 in valu2) {
finalData.push(valu2[name2]);
};
console.log(finalData.toSource());
How do I strip out those key values user1post2: ?
When I check the length,
console.log("length is:" + values.length);
it indicates a length of 1, so if the count starts at zero, then that would be correct. I could set up a for loop that iterates from 0 to i.
I'm not sure what the syntax or property is to reference data inside the array.
You have an array with a single object within. The keys of that object are what you want as an array. So:
var val = [{ /*... your data ...*/ }];
var out = [];
var myBigObject = val[0];
for (var i in myBigObject) {
if (myBigObject.hasOwnProperty(i)) {
out.push(myBigObject[i]);
}
}
console.log(out);
http://jsfiddle.net/5xuLJ/
Is this what you want?
values = [{
user1post2: {
ad: "Car",
ac: 39500,
af: "4",
ah: "klgjoirt3904d",
ab: "Acura",
ae: "2013 ACURA MDX 3.5L V6 AWD 6AT (294 HP)",
ag: "Mint",
aa: "Option2"
},
user1post1: {
ad: "Truck",
ac: 6799,
af: "3",
ah: "ldkfldfjljKey",
ab: "GMC",
ae: "1/2 Ton with plow",
ag: "Mint Looks",
aa: "Option1"
}
}]
out = [];
for(prop in values[0]) {
out.push(prop);
}
console.log(out);
or are you trying to iterate over the actual data inside each property (i.e. loop over user1post2 to get the value ad: "Car" etc)?

Categories