How to delete array element from JSON array of objects by ID - javascript

This is probably quite easy, but giving me trouble. Given this JSON structure:
"playlists" : [
{
"id" : "1",
"owner_id" : "2",
"song_ids" : [
"8",
"32"
]
},
{
"id" : "2",
"owner_id" : "3",
"song_ids" : [
"6",
"8",
"11"
]
},
{
"id" : "3",
"owner_id" : "7",
"song_ids" : [
"7",
"12",
"13",
"16",
"2"
]
}
]
How would you delete an object from the array by key/value? In this case by ID? playlist.splice(1,1)? playlist.delete(id)? Not sure how to do this elegantly. Let's say I wish to delete the element with ID = 3, how to get this result:
"playlists" : [
{
"id" : "1",
"owner_id" : "2",
"song_ids" : [
"8",
"32"
]
},
{
"id" : "2",
"owner_id" : "3",
"song_ids" : [
"6",
"8",
"11"
]
}
]

Using Array.filter, you can filter out elements that don't match a certain condition. For example:
const result = playlists.filter(playlist => playlist.id !== '2');
Here's a working demo:
/* Example Data */
const playlists = [
{
"id" : "1",
"owner_id" : "2",
"song_ids" : [ "8", "32"]
},
{
"id" : "2",
"owner_id" : "3",
"song_ids" : ["6", "8","11" ]
}
];
/* Takes a list of playlists, and an ID to remove */
const removePlaylistById = (plists, id) =>
plists.filter(playlist => playlist.id !== id);
/* Removes playlist ID 2 from list, prints result */
const result = removePlaylistById(playlists, '2');
console.log(result);
Another option, would be to use Array.findIndex to get the index of an element with given ID, then use Array.splice to remove that element. This will modify the array, without the need for a copy.
For example:
const indexToRemove = playlists.findIndex((pl) => pl.id === '2');
playlists.splice(indexToRemove, 1);

Related

Best way to transform a list with a specific structure into a list of objects

This is the list that contains in the first key figure, all the attributes of my desired object, and in the later key figures, contains the value for each attribute in the line.:
[
[
"goalId",
"holderId",
"balance",
"taxes",
"netBalance",
"investmentIncome"
],
[
"1",
"1",
"33333333",
"150",
"150",
"1"
],
[
"5",
"5",
"1000",
"150",
"150",
"1"
],
[
"7",
"7",
"1000",
"150",
"150",
"1"
],
[
"11",
"12",
"1000",
"150",
"150",
"1"
],
[
""
]
]
And I want to turn the above list into a list of objects like this:
[
{
"goalId":1,
"holderId":1,
"balance":33333333,
"taxes":150,
"netBalance":150,
"investmentIncome":1
},
{
"goalId":5,
"holderId":5,
"balance":1000,
"taxes":150,
"netBalance":150,
"investmentIncome":1
},
{
"goalId":7,
"holderId":7,
"balance":1000,
"taxes":150,
"netBalance":150,
"investmentIncome":1
},
{
"goalId":11,
"holderId":12,
"balance":1000,
"taxes":150,
"netBalance":150,
"investmentIncome":1
}
]
I've already done it, but I think there's a better way to do it. The code was like this:
// Assuming that the variable already has the list loaded
const attributes = unformattedList[0];
unformattedList.splice(0, 1);
const arrayOfObjects = unformattedList.map(rawValue => {
const object = {};
rawValue.map((value, index) => {
object[attributes[index]] = value;
});
return object;
});
You shouldn't use .map() if your sole use-case for it is to iterate and cause side-effects - .forEach() is better for that task. However, you can still use .map() for this type of problem if you use it as intended (i.e use the new array it returns). First, you can get the keys of your objects by popping the first element from you array using .shift(). Then, you can .map() each inner array of values to an object (formed using Object.assign()), which contains all your values from the inner array:
const arr = [[ "goalId", "holderId", "balance", "taxes", "netBalance", "investmentIncome" ], [ "1", "1", "33333333", "150", "150", "1" ], [ "5", "5", "1000", "150", "150", "1" ], [ "7", "7", "1000", "150", "150", "1" ], [ "11", "12", "1000", "150", "150", "1" ], [ "" ]];
const keys = arr.shift();
const res = arr.filter(({length}) => length > 1).map(
vals => Object.assign({}, ...vals.map((v, i) => ({[keys[i]]: +v})))
)
console.log(res);
Above I am also using .filter(({length}) => length > 1)) to remove the uneeded [""] from your array. This will also remove empty arrays as well.

I need to merge objects. They all have the same keys but differing numerical values. I need to get the sum of values for each key

New to JS and programming in general. I've tried numerous solutions on SO and other resources and cannot seem to figure this out. I have twenty or more objects representing user 'votes'. The all have the same keys and different values depending on the user input. I need to 'tally the votes' by summing the different values and return a single object.
Example:
{
"Seattle" : "1",
"Chicago" : "2",
"New York" : "3"
}
{
"Chicago" : "1",
"New York" : "2",
"Seattle" : "3"
}
{
"New York" : "1",
"Chicago" : "2",
"Seattle" : "3"
}
I'd like the three objects above to be distilled to this:
{
"New York" : "6",
"Seattle" : "7",
"Chicago" : "5"
}
If you could point me in the right direction I'd greatly appreciate it!
Assuming your votes are in an array, you can reduce it into a single object:
const votes = [
{
"Seattle" : "1",
"Chicago" : "2",
"New York" : "3"
},
{
"Chicago" : "1",
"New York" : "2",
"Seattle" : "3"
},
{
"New York" : "1",
"Chicago" : "2",
"Seattle" : "3"
}
];
const tally = votes.reduce((a, e) => {
for (const p in e) {
a[p] = a[p] + (+e[p]) || +e[p];
}
return a;
}, {})
console.log(tally);
Another option with reduce/keys/map which somewhat more functional looking:
const objs = [{
"Seattle": "1",
"Chicago": "2",
"New York": "3"
},
{
"Chicago": "1",
"New York": "2",
"Seattle": "3"
},
{
"New York": "1",
"Chicago": "2",
"Seattle": "3"
}
]
var result = objs.reduce((r, c) => Object.keys(r).map((x) => r[x] = +r[x] + (+c[x])) && r)
console.log(result)

Adding another object inside an existing JSON

I'm basically trying to save data into a json,
so basically:
{
"userid1": {
"name" : "user1",
"wins" : "21",
"loss" : "0",
"leaderboard" : "1"
},
"userid2": {
"name" : "user2",
"wins" : "0",
"loss" : "0",
"leaderboard" : "0"
},
// how do you push another object, let's say; this time; userid3 which would look like this.
// "userid3": {
// "name" : "user3",
// "wins" : "0",
// "loss" : "0",
// "leaderboard" : "0"
// }
// (using javascript, from another file; let's say it's called "datasave.js")
// here?
}
I want to add another object instead of rewriting the whole thing. How do I do that?
This is a json file on it's own, there's another .js file and that's where the json file gets parsed. I want to add the object from there.
I've got it working somehow now. imgur.com/zQTJ11K; there's a var called "id" and that id's the userId, how do I change the "id" in the picture to the userId?
output = {
"userid1": {
"name" : "user1",
"wins" : "21",
"loss" : "0",
"leaderboard" : "1"
},
"userid2": {
"name" : "user2",
"wins" : "0",
"loss" : "0",
"leaderboard" : "0"
}
};
u3 = {
"name" : "user2",
"wins" : "0",
"loss" : "0",
"leaderboard" : "0"
};
output.userid3 = u3;
console.log(output);
you can use Object.assign
const result = Object.assign(data, objToAdd);
Or bracket notation
data['userId3'] = obj
Or dot notation
data.userId3 = obj
const data = {
"userid1": {
"name": "user1",
"wins": "21",
"loss": "0",
"leaderboard": "1"
},
"userid2": {
"name": "user2",
"wins": "0",
"loss": "0",
"leaderboard": "0"
}
}
const obj = {
"userid3": {
"name": "user3",
"wins": "0",
"loss": "0",
"leaderboard": "0"
}
}
Object.assign(data, obj);
console.log(data)
you can import another file into your file using js import.you can import your objects too
you can use javascript spread syntax to combine two objects into one
var object1={name:"xyz"}
var object2={surname:"abc"}
then object1={...object1,...object2} // object={name:"xyz",surname:"abc"}

React : Filter or map Object by iterating through list of objects

I have list of CutomerType objects and Customer object. Customer object has the cutomerType id property on it. Based on the customer type id on customer object I have to loop over or map the right customerType object and disaplay the name code.
[ {
"id" : "5436d5fd-e3ea-4e09-be4a-a80967cd72e5",
"code" : "0",
"name" : "UN"
}, {
"id" : "674b76b8-f1ac-5c14-e053-ce5e1cac867d",
"code" : "1",
"name" : "NON-UN"
}, {
"id" : "674b76b8-f1ad-5c14-e053-ce5e1cac867d",
"code" : "2",
"name" : "COS-UN"
}, {
"id" : "674b76b8-f1ae-5c14-e053-ce5e1cac867d",
"code" : "NA",
"name" : NA"
} ]
Customer
{
"id" : "1",
"name": "Jhon",
"type": "5436d5fd-e3ea-4e09-be4a-a80967cd72e5",
}
This is what you could do.
const customerCodeArray = [{
"id": "5436d5fd-e3ea-4e09-be4a-a80967cd72e5",
"code": "0",
"name": "UN"
}, {
"id": "674b76b8-f1ac-5c14-e053-ce5e1cac867d",
"code": "1",
"name": "NON-UN"
}, {
"id": "674b76b8-f1ad-5c14-e053-ce5e1cac867d",
"code": "2",
"name": "COS-UN"
}, {
"id": "674b76b8-f1ae-5c14-e053-ce5e1cac867d",
"code": "NA",
"name": "NA"
}]
const customer = {
"id": "1",
"name": "Jhon",
"type": "5436d5fd-e3ea-4e09-be4a-a80967cd72e5",
};
const getCustomerCode = (type) => {
const filterList = customerCodeArray.filter((obj) => obj.id === type);
if (filterList.length > 0) {
return filterList[0];
}
}
console.log(getCustomerCode(customer.type));
Hope this is clear, if not feel free to ask
const loop = // whole array;
const customer = // customer object
loop.find(el => el.id === customer.type).name
const filteredResult = customerCodeArray.filter(type => type.id === Customer.type);
console.log(filteredResult[0].name);

insert in subdocument with mongoDB

I have the following document in the collection:
"_id" : "2",
"workspace" : [{
"name" : "1",
"widgets" : [ ]
},{
"name" : "2",
"widgets" : [ ]
},{
"name" : "3",
"widgets" : [ ]
},{
"name" : "4",
"widgets" : [ ]
}
]}
How can I insert {id: "1", blabla: "blabla"} in "widgets" for the "name" 3?
In comparison to a previous answer which just inserts everything into the root of the document, here is a correct way to do this with positional operator:
db.t.update({
"_id" : "2",
"workspace.name" : "3"
},{
$push: {
'workspace.$.widgets' : {
id: "2",
blabla: "blabla"
}
}
});

Categories

Resources