Adding key in an array by finding a value AngularJS - javascript

I am trying to add an extra key in a JSON array by searching any key value.
Example JSON:-
[
{
"$id": "2025",
"ID": 41,
"Name": "APPLE"
},
{
"$id": "2026",
"ID": 45,
"Name": "MANGO"
},
{
"$id": "2027",
"ID": 48,
"Name": "GUAVA"
}
]
Suppose I have to add a new key pair example "Price": 50 after "Name": "MANGO" or by finding ID ID": 45. So my expected new JSON will be :-
[
{
"$id": "2025",
"ID": 41,
"Name": "APPLE"
},
{
"$id": "2026",
"ID": 45,
"Name": "MANGO",
"Price": 50
},
{
"$id": "2027",
"ID": 48,
"Name": "GUAVA"
}
]
It must add on the object related to matched search key.
So, I am not able to find out any function related to the issue.

You can run a loop and check the condition and then add a property to an object. Here is a running code snippet. You can read here more about JavaScript Objects
var myarray = [
{
"$id": "2025",
"ID": 41,
"Name": "APPLE"
},
{
"$id": "2026",
"ID": 45,
"Name": "MANGO"
},
{
"$id": "2027",
"ID": 48,
"Name": "GUAVA"
}
]
for(var i=0;i<myarray.length;i++){
if(myarray[i].$id === "2025" || myarray[i].Name === "APPLE"){
var data = myarray[i];
data.price = 50
}
}
console.log(myarray)

You can use array#find to compare the ID. Then based that you can add Price key to the object.
let arr = [ { "$id": "2025", "ID": 41, "Name": "APPLE" }, { "$id": "2026", "ID": 45, "Name": "MANGO" }, { "$id": "2027", "ID": 48, "Name": "GUAVA" } ],
id = 45,
obj = arr.find(({ID}) => ID === id);
if(obj);
obj.Price = 50;
console.log(arr);

You can try with:
data.find(item => item.ID === 45).price = 50;
To cover the case if item is not available:
(data.find(item => item.ID === 45) || {}).price = 50;

Related

Is there any way to filter objects from array of objects that should include all selected values in javascript

Here i have skills array and employees array and i am trying to get the employees that includes all the skills that are included in skills array using reduce, filter or find method. I am trying to stored the filtered employees in filteredItems but got stuck in it.
filteredItems = Skills?.length>0 ?
Employees?.filter((item) => {
return item.Skills.find((ele) => {
return Skills.find((el) => {
if(el.value === ele.id){
return ele
}
})
})
}) : []
Below are the arrays mentioned.
Skills Array
[
{
"value": 6,
"label": "Marketing"
},
{
"value": 20,
"label": "Golang"
}
]
Employees Array
[
{
"name": "Hassan",
"id": 56,
"Skills": [
{
"id": 20,
"name": "Golang",
},
],
},
{
"name": "Haroon",
"id": 95,
"Skills": [
{
"id": 6,
"name": "Marketing",
},
{
"id": 20,
"name": "Golang",
},
],
},
]
For example, in above scenario of arrays it should return employee of id of 95 not return employee of id 56 because it includes skills but not all that are mention in skills array.
I found it easier to first encapsulate an array of skill IDs to search for.
let skillIds = Skills.map(s => s.value);
Then I filtered and compared the end result to the length of the skill Ids array:
let filteredItems = Skills?.length > 0 ?
Employees?.filter(item => item.Skills.filter( s =>
skillIds.includes(s.id)).length==skillIds.length): []
let Skills = [{
"value": 6,
"label": "Marketing"
}, {
"value": 20,
"label": "Golang"
}]
let Employees = [{
"name": "Hassan",
"id": 56,
"Skills": [{
"id": 20,
"name": "Golang",
}],
}, {
"name": "Haroon",
"id": 95,
"Skills": [{
"id": 6,
"name": "Marketing",
},
{
"id": 20,
"name": "Golang",
},
],
}, ]
let skillIds = Skills.map(s => s.value);
let filteredItems = Skills?.length > 0 ?
Employees?.filter(item => item.Skills.filter( s => skillIds.includes(s.id)).length==skillIds.length): []
console.log(filteredItems)
You could create another property in the employees array.. call it "QUalified". Default it to true, then set it to false when the employee doesn't have a skill in the skills array.
let arSkills = [
{
"value": 6,
"label": "Marketing"
},
{
"value": 20,
"label": "Golang"
}
];
let arEmp = [
{
"name": "Hassan",
"id": 56,
"Skills": [
{
"id": 20,
"name": "Golang",
},
],
},
{
"name": "Haroon",
"id": 95,
"Skills": [
{
"id": 6,
"name": "Marketing",
},
{
"id": 20,
"name": "Golang",
},
],
},
];
arEmp.forEach(ele =>{
ele.Qualified = true;
let arTmp = [];
for(let {id} of ele.Skills)
arTmp.push(id)
for(let {value} of arSkills)
if(!arTmp.includes(value))
ele.Qualified = false
});
let arQual = arEmp.filter((ele) =>{
return ele.Qualified
});
console.log(arQual);

rename all key's objects JS

I want to rename some of my key's object but with a map it sounds quite difficult (I'm a newbie) here is my array :
"platforms": [
{
"id": 6,
"name": "PC (Microsoft Windows)"
},
{
"id": 11,
"name": "Xbox"
},
{
"id": 14,
"name": "Mac"
},
{
"id": 48,
"name": "PlayStation 4"
},
{
"id": 130,
"name": "Nintendo Switch"
}
],
And this is what i want it to be :
"platforms": [
{
"id": 6,
"name": "PC"
},
{
"id": 11,
"name": "Xbox"
},
{
"id": 14,
"name": "Mac"
},
{
"id": 48,
"name": "PS4"
},
{
"id": 130,
"name": "Switch"
}
],
And here is my code :
const renderedResults = results.map((result, index) => {
const platformSliced = result.platforms.slice(0,3);
return (
{platformSliced.map((platform) =>
<span className="main-game-card-platform">
{platform.name}.replace('PC (Windows Microsoft)', 'PC')
</span>
)}
);
});
It doesn't work maybe I should do a condition, but how can I write it ? Thank you
Create an object where the keys are the strings you want changed, and the values the strings that should replace the old string.
With .map() method, return a new object for each item, where the id is unchanged. The name property should look first in the new "rewrites" object if the value of name exists as a key in the object. If it does, then the value should be used, otherwise there is no rewrite and the old name should be used.
const rewrites = {
"PC (Microsoft Windows)": 'PC',
"PlayStation 4": 'PS4',
"Nintendo Switch": 'Switch'
};
const platforms = [
{
"id": 6,
"name": "PC (Microsoft Windows)"
},
{
"id": 11,
"name": "Xbox"
},
{
"id": 14,
"name": "Mac"
},
{
"id": 48,
"name": "PlayStation 4"
},
{
"id": 130,
"name": "Nintendo Switch"
}
];
const rewrittenPlatforms = platforms.map(({ id, name }) => ({
id,
name: rewrites[name] ?? name // Use rewritten name, if present, otherwise use old name.
}));
console.log(rewrittenPlatforms);

How to get the respective JSON object based on id

how to get the respective nested JSON object based on Id. For example below is my complete JSON.
[
{
"id": 1,
"title": "ASD Headquarters",
"items": [
{
"id": 11,
"title": "San Jose",
"items": [
{
"id": 13,
"title": "Jensen Chapman's Team",
"items": [
{
"id": 14,
"title": "Jimmy John"
},
{
"id": 15,
"title": "Daniel Mills"
},
{
"id": 16,
"title": "Chris Boden"
}
]
}
]
},
{
"id": 12,
"title": "Irvine",
"items": [
{
"id": 23,
"title": "Tracey Chapman's Team",
"items": [
{
"id": 24,
"title": "San Jesus"
},
{
"id": 25,
"title": "Fat Albert"
},
{
"id": 26,
"title": "Connor McDavid"
}
]
}
]
},
{
"id": 30,
"title": "San Diego",
"items": [
{
"id": 31,
"title": "Duran Duran's Team",
"items": [
{
"id": 32,
"title": "Amberlynn Pinkerton"
},
{
"id": 33,
"title": "Tony Mejia"
},
{
"id": 34,
"title": "Richard Partridge"
},
{
"id": 35,
"title": "Elliot Stabler"
}
]
},
{
"id": 40,
"title": "Steely Dan's Team",
"items": [
{
"id": 36,
"title": "Tony Stark"
},
{
"id": 37,
"title": "Totally Rad"
},
{
"id": 38,
"title": "Matt Murdock"
},
{
"id": 39,
"title": "Stan Lee"
}
]
}
]
}
]
}
]
From the above json how do i filter only particular nested object which have id as 11 => {"id": 11} using underscore.js
Output which i required is : {
"id":11,
"title":"San Jose",
"items":[
{
"id":13,
"title":"Jensen Chapman's Team",
"items":[
{
"id":14,
"title":"Jimmy John"
},
{
"id":15,
"title":"Daniel Mills"
},
{
"id":16,
"title":"Chris Boden"
}
]
}
]
}
You can use a recursive algorithm to look for an object in the current array as well as the nested ones.
var data = [{"id":1,"title":"ASD Headquarters","items":[{"id":11,"title":"San Jose","items":[{"id":13,"title":"Jensen Chapman's Team","items":[{"id":14,"title":"Jimmy John"},{"id":15,"title":"Daniel Mills"},{"id":16,"title":"Chris Boden"}]}]},{"id":12,"title":"Irvine","items":[{"id":23,"title":"Tracey Chapman's Team","items":[{"id":24,"title":"San Jesus"},{"id":25,"title":"Fat Albert"},{"id":26,"title":"Connor McDavid"}]}]},{"id":30,"title":"San Diego","items":[{"id":31,"title":"Duran Duran's Team","items":[{"id":32,"title":"Amberlynn Pinkerton"},{"id":33,"title":"Tony Mejia"},{"id":34,"title":"Richard Partridge"},{"id":35,"title":"Elliot Stabler"}]},{"id":40,"title":"Steely Dan's Team","items":[{"id":36,"title":"Tony Stark"},{"id":37,"title":"Totally Rad"},{"id":38,"title":"Matt Murdock"},{"id":39,"title":"Stan Lee"}]}]}]}];
console.log(find(12, data));
function find(id, [head, ...tail]) {
if (!head)
return null;
return checkObj(id, head) || find(id, tail);
}
function checkObj(id, obj) {
return obj.id === id ? obj : find(id, obj.items || [])
}
This also uses parameter destructuring in order to conveniently separate the "head" of the array from its "tail".
It could also be done within a single function.
var data = [{"id":1,"title":"ASD Headquarters","items":[{"id":11,"title":"San Jose","items":[{"id":13,"title":"Jensen Chapman's Team","items":[{"id":14,"title":"Jimmy John"},{"id":15,"title":"Daniel Mills"},{"id":16,"title":"Chris Boden"}]}]},{"id":12,"title":"Irvine","items":[{"id":23,"title":"Tracey Chapman's Team","items":[{"id":24,"title":"San Jesus"},{"id":25,"title":"Fat Albert"},{"id":26,"title":"Connor McDavid"}]}]},{"id":30,"title":"San Diego","items":[{"id":31,"title":"Duran Duran's Team","items":[{"id":32,"title":"Amberlynn Pinkerton"},{"id":33,"title":"Tony Mejia"},{"id":34,"title":"Richard Partridge"},{"id":35,"title":"Elliot Stabler"}]},{"id":40,"title":"Steely Dan's Team","items":[{"id":36,"title":"Tony Stark"},{"id":37,"title":"Totally Rad"},{"id":38,"title":"Matt Murdock"},{"id":39,"title":"Stan Lee"}]}]}]}];
console.log(find(12, data));
function find(id, [head, ...tail]) {
if (!head)
return null;
if (head.id === id)
return head;
return find(id, head.items || []) || find(id, tail);
}

Find object index from array

I'm trying to find out selected object index from array
But it always return -1 don't know why?
Here is I'm trying to do
I have following array in which their are multiple objects
var data = [{
"name": "abc",
"age": 25,
"school": "xyz pqr"
},
{
"name": "abc1",
"age": 26,
"school": "xyz pqr"
},
{
"name": "abc2",
"age": 27,
"school": "xyz pqr"
}]
And here is my another array that are selected by user
var dList = [{
"name": "abc",
"age": 25,
"school": "xyz pqr",
"isChecked": true
}]
Now I want to find out selected object index from data array and remove this object from that array
if (dList.length > 0) {
for (let i=0; i<dList.length; i++){
delete dList[i]['isChecked']
console.log(dList[i])
console.log(data[0])
console.log(dList[i] == data[0])
let index = data.indexOf(dList[i]);
console.log(index)
data.splice(index, 1);
}
}
Here is just a simple implementation:
if (dList.length > 0) {
for (let i=0; i<dList.length; i++) {
delete dList[i]['isChecked']
console.log(dList[i])
console.log(data[0])
console.log(JSON.stringify(dList[i]) === JSON.stringify(data[0]))
let index = data.findIndex(()=>dList[i]);
console.log(index)
data.splice(index, 1);
}
}
Comparing the objects can be done by just converting it into string using JSON.stringify(ObjectName).
Second instead of using indexOf use findIndex.
Here is the main difference between indexOf and findIndex.
You can only compare two primitive types only so you will not be able to get the index of the object by comparing it.
You should instead compare some primary key which will be unique for each object inside the array.
var data = [{
"name": "abc",
"age": 25,
"school": "xyz pqr"
},
{
"name": "abc1",
"age": 26,
"school": "xyz pqr"
},
{
"name": "abc2",
"age": 27,
"school": "xyz pqr"
}];
var index = data.findIndex(x => x.name=="abc2");
console.log(index);
this is going to meet your demand, a more universal version,if you got unique id,that is going to be the best choice:
var data = [{
"name": "abc",
"age": 25,
"school": "xyz pqr"
},
{
"name": "abc1",
"age": 26,
"school": "xyz pqr"
},
{
"name": "abc2",
"age": 27,
"school": "xyz pqr"
}
];
var dList = [{
"name": "abc",
"age": 25,
"school": "xyz pqr",
"isChecked": true
}];
dList.forEach(function(obj) {
delete obj.isChecked;
data.splice(data.findIndex((o) => {
return Object.getOwnPropertyNames(obj).every(p => obj[p] === o[p]);
}), 1);
});
console.log(data);
another way:
var data = [{
"name": "abc",
"age": 25,
"school": "xyz pqr"
},
{
"name": "abc1",
"age": 26,
"school": "xyz pqr"
},
{
"name": "abc2",
"age": 27,
"school": "xyz pqr"
}
];
var dList = [{
"name": "abc",
"age": 25,
"school": "xyz pqr",
"isChecked": true
}];
dList.forEach(function(obj) {
delete obj.isChecked;
data.splice(data.findIndex((o) => o.name === obj.name && o.age === obj.age && o.school === obj.school && o.school === obj.school), 1);
});
console.log(data);
unrecommended way:
var data = [{
"name": "abc",
"age": 25,
"school": "xyz pqr"
},
{
"name": "abc1",
"age": 26,
"school": "xyz pqr"
},
{
"name": "abc2",
"age": 27,
"school": "xyz pqr"
}
];
var dList = [{
"name": "abc",
"age": 25,
"school": "xyz pqr",
"isChecked": true
}];
dList.forEach(function(obj) {
delete obj.isChecked;
data.splice(data.findIndex((o) => JSON.stringify(o) === JSON.stringify(obj)), 1);
});
console.log(data);
You can use this also
var data = [{
"name": "abc",
"age": 25,
"school": "xyz pqr"
},
{
"name": "abc1",
"age": 26,
"school": "xyz pqr"
},
{
"name": "abc2",
"age": 27,
"school": "xyz pqr"
}];
var dList = [{
"name": "abc",
"age": 25,
"school": "xyz pqr",
"isChecked": true
}]
console.log(data.map(function(d){
return d.name;
}).indexOf(dList[0].name));
You cannot compare two Object Notations(JSON). To compare two JSONs you need to first stringify the object, then JavaScript can compare the two objects for you.
Here is a simple code for you to get what you desire.
if (dList.length > 0) {
for(var i=0; i<data.length; i++){
for(var j=0; j<dList.length; j++){
delete dList[j]['isChecked'];
if(JSON.stringify(data[i]) === JSON.stringify(dList[j])){
let index = data.indexOf(data[i]);//Gets the index of the array
data.splice(index, 1);
console.log(data);
}else{
console.log('Data Not Matched in Array');
}
}
}
}
There is no generic means to determine that an object is equal to another in the sense. Please see Equality comparisons for more information.
You can find and remove objects like below:
Array.prototype.remove = function(elem) {
var indexElement = this.findIndex(el => el.name === elem.name);
console.log(indexElement);
if (indexElement != -1)
this.splice(indexElement, 1);
return this;
};
data.remove(dList[0]);
console.log(data);
Online demo (jsFiddle)
var result= data.filter((item, i, self) => {
if (item.name === 'abc2') {
return { itemIndex: i, obj: item }
}
});
var output = result.map(r => { console.log(r.itemIndex) })
console.log(output);
This will return all objects in which name is abc2. findIndex array method will always return 1 index that might not be the case as people can have the same name.

Return filtered array js

I have an Array of Objects, each containing Array and Objects, like so:
data = [{
"id": 10022,
"date": "2017-12-31T03:44:19.963808Z",
"bought_beats": [{
"id": 10034,
"beat": {
"id": 6334,
"name": "Glass",
"producer": {
"id": 23,
"display_name": "MadReal",
}
},
"license": {
"id": 10034,
"name": "Premium",
},
}, {
"id": 894,
"beat": {
"id": 6334,
"name": "Other Name",
"producer": {
"id": 25,
"display_name": "Other Name",
}
},
"license": {
"id": 10034,
"name": "Premium",
},
}]
}, {
"moredata": "stuff"
}]
And I need to filter the bought_beats property, and only return beat, if beat.producer.id === 23
This is what I have but it's clearly not working
data.forEach(order => {
return order.bought_beats.filter(item => item.beat.id === producerId)
})
===========
Edit1:
Trying this. It "works", but it also removed some properties (id & date) from each order object (which is each index of data), so I have objects that only contain the array of "bought_beats"
var res = data.map(item => item.bought_beats.filter(item => item.beat.producer.id === 23))
========
Edit2
This seems to be 1 solution, it maintains the array and object structure the same, while it removes those unwanted elements from the bought_beats array.
data.forEach(order => {
let elementToRemoveIndex = order.bought_beats.findIndex(item => item.beat.producer.id !== 23)
order.bought_beats.splice(elementToRemoveIndex, 1)
})
Thanks #Pac0 for the continuous help
use .find over data.bought_beats since its an array,
DEMO
var data = [{
"id": 10022,
"date": "2017-12-31T03:44:19.963808Z",
"bought_beats": [{
"id": 10034,
"beat": {
"id": 6334,
"name": "Glass",
"producer": {
"id": 23,
"display_name": "MadReal",
}
},
"license": {
"id": 10034,
"name": "Premium",
},
}, {
"id": 894,
"beat": {
"id": 6334,
"name": "Other Name",
"producer": {
"id": 25,
"display_name": "Other Name",
}
},
"license": {
"id": 10034,
"name": "Premium",
},
}]
}, {
"moredata": "stuff"
}];
var result = data.find(dat => dat.bought_beats.some(item => item.beat.producer.id === 23));
console.log(result);
If I understood correctly, this should be what you want :
// project each object to its bought_beats / beats part
var beatsArrays = data.filter(x => x.bought_beats).map(x => x.bought_beats);
// flatten the array of arrays of beats into a simple array of beats
var beats = [].concat.apply([],beatsArrays).map(x => x.beat);
// filter
var relevantBeats = beats.filter(item => item.producer.id === 23);
// serve with a cherry in a sugar-frost cocktail glass (happy new year ! )
console.log(relevantBeats);
Snippet :
data = [{
"id": 10022,
"date": "2017-12-31T03:44:19.963808Z",
"bought_beats": [{
"id": 10034,
"beat": {
"id": 6334,
"name": "Glass",
"producer": {
"id": 23,
"display_name": "MadReal",
}
},
"license": {
"id": 10034,
"name": "Premium",
},
}, {
"id": 894,
"beat": {
"id": 6334,
"name": "Other Name",
"producer": {
"id": 25,
"display_name": "Other Name",
}
},
"license": {
"id": 10034,
"name": "Premium",
},
}]
}, {
"moredata": "stuff"
}];
// project each object to its bought_beats / beats part
var beatsArrays = data.filter(x => x.bought_beats).map(x => x.bought_beats);
// flatten the array of arrays of beats into a simple array of beats
var beats = [].concat.apply([],beatsArrays).map(x => x.beat);
// filter
var relevantBeats = beats.filter(item => item.producer.id === 23);
// serve with a cherry in a sugar-frost cocktail glass (happy new year ! )
console.log(relevantBeats);
// for each order
data.forEach(order => {
// we loop thorugh the bought beats array
order.bought_beats.forEach((item, index) => {
// and if there's a beat from another producer, we remove it
if (item.beat.producer.id !== producerId) order.bought_beats.splice(index, 1)
})
})

Categories

Resources