Adding an object conditionally inside an array - javascript

I want to add a conditional object inside an array of objects. If the condition is not met, I want it as if that object is not there AT ALL, while keeping the other objects as they are.
Consider the following:
const CardBuildingBlock: FC = () => {
const type = 'typeA';
const typesOfCards = [
{name: 'Card A'
size: 'Medium'
action: 'make'},
{name: 'Card B'
size: 'Small'
action: 'break'},
{name: 'Card C'
size: 'Large'
action: 'build'},
//I tried doing the following but it doesn't work
type == 'typeA' ? null : {
name: 'Card A'
size: 'Medium'
action: 'make'},
];
return(
typeOfCards.map(({name, size, action}) => (
<BuildCard
name = {name}
size = {size}
action = {action}
/>
)
)};
Please Help.!!!
Thanks for the help.

From what I understood, you want to filter away all the elements of the array given a condition. What I would do is adding a new key to the object specifying if it should be displayed, and then filter & map.
const typesOfCards = [
{ name: "Card A", size: "Medium", action: "make", type: "typeA" },
...
];
return typesOfCards.filter(card => card.type === "typeA").map(({ name, size, action }) => (
<BuildCard name={name} size={size} action={action} />
));

Easiest way here would be to concat new element to an array. In case condition is true, you will concat new element. Consider this examples:
// using if statement
const type = "typeA";
let additionalCardOfTypeA = {
name: "Card A",
size: "Medium",
action: "make",
};
let typesOfCards = [
{ name: "Card A", size: "Medium", action: "make" },
{ name: "Card B", size: "Small", action: "break" },
{ name: "Card C", size: "Large", action: "build" },
];
if (type === "typeA") {
typesOfCards = typesOfCards.concat(additionalCardOfTypeA);
}
// using ternary operator
const type = "typeA";
let additionalCardOfTypeA = {
name: "Card A",
size: "Medium",
action: "make",
};
let typesOfCards = [
{ name: "Card A", size: "Medium", action: "make" },
{ name: "Card B", size: "Small", action: "break" },
{ name: "Card C", size: "Large", action: "build" },
].concat(
type === "typeA"
? additionalCardOfTypeA
: []
);
Edit
To insert new element in particular place you will have to create additional arrays. First, find a place for your element. Then, create an array that have everything before said index in original, and array that have everything from index to an end. Then concatenate start, new element and end into final array.
const type = "typeA";
let additionalCardOfTypeA = {
name: "Card A",
size: "Medium",
action: "make",
};
let typesOfCards = [
{ name: "Card A", size: "Medium", action: "make" },
{ name: "Card B", size: "Small", action: "break" },
{ name: "Card C", size: "Large", action: "build" },
];
if (type === "typeA") {
let indexForNewElement = getSomehowIndex();
// Getting everything before index
let head = typesOfCards.slice(0, indexForNewElement);
// Getting everything after index
let tail = typesOfCards.slice(indexForNewElement);
typesOfCards = head.concat(additionalCardOfTypeA).concat(tail);
}

Maybe a push would be useful in that case:
type === 'typeA' && typesOfCards.push({
name: 'Card A'
size: 'Medium'
action: 'make'}
)
maybe you might want to include that within a function and it should return the typesOfCards array

Related

How to change data in the object with array of objects in JS [duplicate]

The code below comes from jQuery UI Autocomplete:
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
For example, I want to change the desc value of jquery-ui. How can I do that?
Additionally, is there a faster way to get the data? I mean give the object a name to fetch its data, just like the object inside an array? So it would be something like jquery-ui.jquery-ui.desc = ....
It is quite simple
Find the index of the object using findIndex method.
Store the index in variable.
Do a simple update like this: yourArray[indexThatyouFind]
//Initailize array of objects.
let myArray = [
{id: 0, name: "Jhon"},
{id: 1, name: "Sara"},
{id: 2, name: "Domnic"},
{id: 3, name: "Bravo"}
],
//Find index of specific object using findIndex method.
objIndex = myArray.findIndex((obj => obj.id == 1));
//Log object to Console.
console.log("Before update: ", myArray[objIndex])
//Update object's name property.
myArray[objIndex].name = "Laila"
//Log object to console again.
console.log("After update: ", myArray[objIndex])
You have to search in the array like:
function changeDesc( value, desc ) {
for (var i in projects) {
if (projects[i].value == value) {
projects[i].desc = desc;
break; //Stop this loop, we found it!
}
}
}
and use it like
var projects = [ ... ];
changeDesc ( 'jquery-ui', 'new description' );
UPDATE:
To get it faster:
var projects = {
jqueryUi : {
value: 'lol1',
desc: 'lol2'
}
};
projects.jqueryUi.desc = 'new string';
(In according to Frédéric's comment you shouldn't use hyphen in the object key, or you should use "jquery-ui" and projects["jquery-ui"] notation.)
The best solution, thanks to ES6.
This returns a new array with a replaced description for the object that contains a value equal to "jquery-ui".
const newProjects = projects.map(p =>
p.value === 'jquery-ui'
? { ...p, desc: 'new description' }
: p
);
Using map is the best solution without using extra libraries.(using ES6)
const state = [
{
userId: 1,
id: 100,
title: "delectus aut autem",
completed: false
},
{
userId: 1,
id: 101,
title: "quis ut nam facilis et officia qui",
completed: false
},
{
userId: 1,
id: 102,
title: "fugiat veniam minus",
completed: false
},
{
userId: 1,
id: 103,
title: "et porro tempora",
completed: true
}]
const newState = state.map(obj =>
obj.id === "101" ? { ...obj, completed: true } : obj
);
ES6 way, without mutating original data.
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
}];
//find the index of object from array that you want to update
const objIndex = projects.findIndex(obj => obj.value === 'jquery-ui');
// Make sure to avoid incorrect replacement
// When specific item is not found
if (objIndex === -1) {
return;
}
// make new object of updated object.
const updatedObj = { ...projects[objIndex], desc: 'updated desc value'};
// make final new array of objects by combining updated object.
const updatedProjects = [
...projects.slice(0, objIndex),
updatedObj,
...projects.slice(objIndex + 1),
];
console.log("original data=", projects);
console.log("updated data=", updatedProjects);
You can use $.each() to iterate over the array and locate the object you're interested in:
$.each(projects, function() {
if (this.value == "jquery-ui") {
this.desc = "Your new description";
}
});
given the following data, we want to replace berries in the summerFruits list with watermelon.
const summerFruits = [
{id:1,name:'apple'},
{id:2, name:'orange'},
{id:3, name: 'berries'}];
const fruit = {id:3, name: 'watermelon'};
Two ways you can do this.
First approach:
//create a copy of summer fruits.
const summerFruitsCopy = [...summerFruits];
//find index of item to be replaced
const targetIndex = summerFruits.findIndex(f=>f.id===3);
//replace the object with a new one.
summerFruitsCopy[targetIndex] = fruit;
Second approach: using map, and spread:
const summerFruitsCopy = summerFruits.map(fruitItem =>
fruitItem .id === fruit.id ?
{...summerFruits, ...fruit} : fruitItem );
summerFruitsCopy list will now return an array with updated object.
you can use .find so in your example
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
let project = projects.find((p) => {
return p.value === 'jquery-ui';
});
project.desc = 'your value'
It's easily can be accomplished with underscore/lodash library:
_.chain(projects)
.find({value:"jquery-ui"})
.merge({desc: "new desc"}).value();
Docs:
https://lodash.com/docs#find
https://lodash.com/docs#merge
you need to know the index of the object you are changing. then its pretty simple
projects[1].desc= "new string";
This is another answer involving find.
This relies on the fact that find:
iterates through every object in the array UNTIL a match is found
each object is provided to you and is MODIFIABLE
Here's the critical Javascript snippet:
projects.find( function (p) {
if (p.value !== 'jquery-ui') return false;
p.desc = 'your value';
return true;
} );
Here's an alternate version of the same Javascript:
projects.find( function (p) {
if (p.value === 'jquery-ui') {
p.desc = 'your value';
return true;
}
return false;
} );
Here's an even shorter (and somewhat more evil version):
projects.find( p => p.value === 'jquery-ui' && ( p.desc = 'your value', true ) );
Here's a full working version:
let projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
projects.find( p => p.value === 'jquery-ui' && ( p.desc = 'your value', true ) );
console.log( JSON.stringify( projects, undefined, 2 ) );
const users = [
{ name: "Alex", age: 25 },
{ name: "John", age: 32 },
];
const newUsers = users.map((user) => ({
...user,
age: user.age + 5, // just for example
}));
// newUsers = [
// {name:"Alex" , age:30},
// {name:"John , age:37}
// ]
I think this way is better
const index = projects.findIndex(project => project.value==='jquery-ui');
projects[index].desc = "updated desc";
const state = [
{
userId: 1,
id: 100,
title: "delectus aut autem",
completed: false
},
{
userId: 1,
id: 101,
title: "quis ut nam facilis et officia qui",
completed: false
},
{
userId: 1,
id: 102,
title: "fugiat veniam minus",
completed: false
},
{
userId: 1,
id: 103,
title: "et porro tempora",
completed: true
}]
const newState = state.map(obj =>
obj.id === "101" ? { ...obj, completed: true } : obj
);
Change value with conditions using for each loop
projects.forEach((p,index)=>{
if(index === 1){
p.value = "Updated jquery-ui"
}
})
// using higher-order functions to avoiding mutation
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
// using higher-order functions to avoiding mutation
index = projects.findIndex(x => x.value === 'jquery-ui');
[... projects.slice(0,index), {'x': 'xxxx'}, ...projects.slice(index + 1, projects.length)];
try using forEach(item,index) helper
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
let search_to_change = 'jquery'
projects.forEach((item,index)=>{
if(item.value == search_to_change )
projects[index].desc = 'your description '
})
let users = [
{id: 1, name: 'Benedict'},
{id: 2, name: 'Myles'},
{id: 3, name: 'Happy'},
]
users.map((user, index) => {
if(user.id === 1){
users[index] = {id: 1, name: 'Baba Benny'};
}
return user
})
console.log(users)
What this code does is map over the object and then match the desired
with if statement,
if(user.id === 1)
once there is match somewhere use its index to swap
users[index] = {id: 1, name: 'Baba Benny'};
the object in the array and then return the modified array
You can use map function --
const answers = this.state.answers.map(answer => {
if(answer.id === id) return { id: id, value: e.target.value }
return answer
})
this.setState({ answers: answers })
Here is a nice neat clear answer. I wasn't 100% sure this would work but it seems to be fine. Please let me know if a lib is required for this, but I don't think one is. Also if this doesn't work in x browser please let me know. I tried this in Chrome IE11 and Edge they all seemed to work fine.
var Students = [
{ ID: 1, FName: "Ajay", LName: "Test1", Age: 20},
{ ID: 2, FName: "Jack", LName: "Test2", Age: 21},
{ ID: 3, FName: "John", LName: "Test3", age: 22},
{ ID: 4, FName: "Steve", LName: "Test4", Age: 22}
]
Students.forEach(function (Student) {
if (Student.LName == 'Test1') {
Student.LName = 'Smith'
}
if (Student.LName == 'Test2') {
Student.LName = 'Black'
}
});
Students.forEach(function (Student) {
document.write(Student.FName + " " + Student.LName + "<BR>");
});
Output should be as follows
Ajay Smith
Jack Black
John Test3
Steve Test4
Assuming you wanted to run a bit more complicated codes during the modification, you might reach for an if-else statement over the ternary operator approach
// original 'projects' array;
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
// modify original 'projects' array, and save modified array into 'projects' variable
projects = projects.map(project => {
// When there's an object where key 'value' has value 'jquery-ui'
if (project.value == 'jquery-ui') {
// do stuff and set a new value for where object's key is 'value'
project.value = 'updated value';
// do more stuff and also set a new value for where the object's key is 'label', etc.
project.label = 'updated label';
// now return modified object
return project;
} else {
// just return object as is
return project;
}
});
// log modified 'projects' array
console.log(projects);
We can also use Array's map function to modify object of an array using Javascript.
function changeDesc(value, desc){
projects.map((project) => project.value == value ? project.desc = desc : null)
}
changeDesc('jquery', 'new description')
The power of javascript destructuring
const projects = [
{
value: 'jquery',
label: 'jQuery',
desc: 'the write less, do more, JavaScript library',
icon: 'jquery_32x32.png',
anotherObj: {
value: 'jquery',
label: 'jQuery',
desc: 'the write less, do more, JavaScript library',
icon: 'jquery_32x32.png',
},
},
{
value: 'jquery-ui',
label: 'jQuery UI',
desc: 'the official user interface library for jQuery',
icon: 'jqueryui_32x32.png',
},
{
value: 'sizzlejs',
label: 'Sizzle JS',
desc: 'a pure-JavaScript CSS selector engine',
icon: 'sizzlejs_32x32.png',
},
];
function createNewDate(date) {
const newDate = [];
date.map((obj, index) => {
if (index === 0) {
newDate.push({
...obj,
value: 'Jquery??',
label: 'Jquery is not that good',
anotherObj: {
...obj.anotherObj,
value: 'Javascript',
label: 'Javascript',
desc: 'Write more!!! do more!! with JavaScript',
icon: 'javascript_4kx4k.4kimage',
},
});
} else {
newDate.push({
...obj,
});
}
});
return newDate;
}
console.log(createNewDate(projects));
We can change in the following way
const oldArray = [{username: gopal, age: 20}, {username: gopi, age: 21}]
const obj = {username: gopal, age: 25}
const result = oldArray.map(d => d.username === 'gopi' ? d.age = obj.age : d)
Find the index first:
function getIndex(array, key, value) {
var found = false;
var i = 0;
while (i<array.length && !found) {
if (array[i][key]==value) {
found = true;
return i;
}
i++;
}
}
Then:
console.log(getIndex($scope.rides, "_id", id));
Then do what you want with this index, like:
$scope[returnedindex].someKey = "someValue";
Note: please do not use for, since for will check all the array documents, use while with a stopper, so it will stop once it is found, thus faster code.
Here i am using angular js. In javascript you can use for loop to find.
if($scope.bechval>0 &&$scope.bechval!=undefined)
{
angular.forEach($scope.model.benhmarkghamlest, function (val, key) {
$scope.model.benhmarkghamlest[key].bechval = $scope.bechval;
});
}
else {
alert("Please sepecify Bechmark value");
}
You can create your specific function like the below, then use that everywhere you need.
var each = (arr, func) =>
Array.from(
(function* (){
var i = 0;
for(var item of arr)
yield func(item, i++);
})()
);
Enjoy..
upsert(array, item) {
const i = array.findIndex(_item => _item.id === item.id);
if (i > -1) {
let result = array.filter(obj => obj.id !== item.id);
return [...result, item]
}
else {
return [...array, item]
};
}
The easiest way is to do this
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
}];
projects.find(data => data.value === "jquery").label ="xxxx"
console.log("------------>",projects)
to update multiple items with the matches use:
_.chain(projects).map(item => {
item.desc = item.value === "jquery-ui" ? "new desc" : item.desc;
return item;
})

Update only one parameter when array is in array React

I have state data like that:
const IssuesList = () => {
const [issuesList, setIssuesList] = useState([
{
groupId: 0,
groupData: "19-07-2016",
groupIssues: [
{
id: 0,
title: "Page changes",
star: true,
},
{
id: 1,
title: "Review of last issues",
star: true,
},
],
},
{
groupId: 1,
groupData: "18-07-2016",
groupIssues: [
{
id: 2,
title: "Visual UI Update Review",
star: false,
},
{
id: 3,
title: "Sidebar changes",
star: false,
},
],
},
{
groupId: 2,
groupData: "15-07-2016",
groupIssues: [
{
id: 4,
title: "Crash update",
star: false,
},
{
id: 5,
title: "Page visual UI Update Review",
star: true,
},
{
id: 6,
title: "Sidebar update",
star: false,
},
],
},
{
groupId: 3,
groupData: "14-07-2016",
groupIssues: [
{
id: 7,
title: "Crash issue",
star: true,
},
{
id: 8,
title: "Visual update & Crash resolve",
star: true,
},
{
id: 9,
title: "Header changes",
star: false,
},
],
},
]);
return (
<div className="issuesList">
{issuesList.map((group) => (
<IssueGroup
key={group.groupId}
group={group}
setIssuesList={setIssuesList}
issuesList={issuesList}
/>
))}
</div>
);
};
export default IssuesList;
I want to change only the star parameter in groupIssues when I click an specyfic icon in a StarIcon component:
const StarIcon = ({ star, index, id, setIssuesList, issuesList, group }) => {
const issueStar = group.groupIssues[index].star;
return (
<svg
xmlns="http://www.w3.org/2000/svg"
//xmlns:xlink="http://www.w3.org/1999/xlink"
preserveAspectRatio="xMidYMid"
width="17"
height="16"
viewBox="0 0 17 16"
className={star ? "staricon filled" : "staricon unfilled"}
onClick={() => {
// setIssuesList() TODO
}}
>
<path
d="M8.500,0.000 L11.301,5.028 L16.999,6.112 L13.033,10.302 L13.753,16.000 L8.500,13.561 L3.247,16.000 L3.967,10.302 L0.001,6.112 L5.699,5.028 L8.500,0.000"
fill={star ? "#21233d" : "#fff"}
stroke={star ? "none" : "#e0e0e0"}
/>
</svg>
);
};
export default StarIcon;
What is the best way to do that in that set of data. I know that spread operator can be helpfull there but i have no idea how to implement that in this data structure when We have array of objects and then we need to get into another array in specyfic object. Maybe changing the data structure will be better or breaking it into two arrays?
Ui view here
You should use a deep copy of the object, spread operator creates only a shallow copy.
Example:
const changeStar = (grpId, issueId) => {
setIssuesList(list => (
list.map(item => (
item.groupId === grpId ?
{...item, groupIssues: item.groupIssues.map(issue => (
issue.id === issueId ? {...issue, star: !issue.star} : issue
))}
: item
)
))
}
Explanation:
map function creates an entirely new array. It will return the elements as it is unless you have matching groupIds. Inside the groupIds, you will change the item based on the id. In the end, you deep copied the object and set an entirely new array with the desired result.
I think you need something like this: copy of current issuesList state. Update the specific star from that copy of state. Set the updated state.
Here is a working sandbox example: https://codesandbox.io/s/bold-browser-cnfw3?file=/src/App.js

Fetch multiple properties from an array of objects and form a new one : Javascript

Been trying to do the following thing:
I have an array of objects ,
var arr = [
{ key: "aabFaa", text: "aabFaa" ,field: "firstName",checked: true},
{ key: "aAaaaa", text: "aAaaaa", field: "firstName", checked: true },
];
Would want to fetch the "text" and "field" out of it and form a new array of objects something like this:
result = [ { "field" : "firstName" , value : "aabFaa" , type :"add"},
{ "field" : "firstName" , value : "aAaaaa" , type: "add"}
]
Here type is hard coded one, where as rest are fetched from the "arr"
Whats the easier way to do this?
Have tried this:
var arr = [
{ key: "aabFaa", text: "aabFaa" ,field: "firstName",checked: true},
{ key: "aAaaaa", text: "aAaaaa", field: "firstName", checked: true },
];
let result = arr.map(a => a.text);
console.log(result)
But this has to be written in multiple lines to get desired properties.Is there an easier approach?
use map with Object Destructuring.
var arr = [
{ key: "aabFaa", text: "aabFaa" ,field: "firstName",checked: true},
{ key: "aAaaaa", text: "aAaaaa", field: "firstName", checked: true },
];
const output = arr.map(({field, text}) => ({field, value: text, type: "add"}));
console.log(output);
Using map seems like a good approach, but you would return a new object and not just one property:
let result = arr.map(a => ({value: a.text, type: 'add', field: a.field}));
let result = arr.map(obj => ({
field: obj.field,
value: obj.text,
type: "add"
}));

Most efficient way to search through an object and array locating match

i have 2 object/arrays:
var objA = {
Red Chair : "DC10291",
USBDongle : "USKI82322",
}
var arrayB = [
{
field: "Yellow Banana",
id: "Yellow Banana"
},
{
field: "Red Chair",
id: "Red Chair"
},
{
field: "Garden",
id: "Garden"
}
]
What i am trying to do is, that if a KEY from objA, e.g. Red Chair, is present in arrayB, then remove it from arrayB.
I have done this:
var arrayClone = _.cloneDeep(arrayB);
var removeThese = [];
Object.keys(arrayClone).forEach(function(p) {
removeThese.push(p)
});
removeThese.forEach(function(remove) {
arrayB.forEach(function(item) {
if(item.id === remove) {
delete objA[remove];
}
});
});
The above works as expected, however is this the most effieicnt? Reasone i ask is because looping throuhg and array within an array loop doesnt feel the best practice? And will have performance impact
You can simply filter it, like this
_.filter(arrayB, obj => !objA.hasOwnProperty(obj.field))
// [ { field: 'Yellow Banana', id: 'Yellow Banana' },
// { field: 'Garden', id: 'Garden' } ]
This uses ES2015's Arrow function syntax. You can write the same with a normal function like this
arrayB.filter(function(obj) {
return !objA.hasOwnProperty(obj.field);
});
// [ { field: 'Yellow Banana', id: 'Yellow Banana' },
// { field: 'Garden', id: 'Garden' } ]
We are basically filtering out all the objects whose field value is a key in objA.
If you would like to keep the original arrayB and get a reduced version of it according to your condition then Array.prototype.reduce() does that with O(n) time complexity. However if you would like to perform this operation in place then Array.prototype.reduceRight() does that with O(n) time complexity.
var objA = {
"Red Chair" : "DC10291",
"USBDongle" : "USKI82322",
},
arrayB = [
{
field: "Yellow Banana",
id: "Yellow Banana"
},
{
field: "Red Chair",
id: "Red Chair"
},
{
field: "Garden",
id: "Garden"
}
],
arrayC = arrayB.reduce((p,c) => !objA[c.field] ? p.concat(c) : p, []);
console.log(arrayC);
arrayB.reduceRight((p,c,i,a) => (p[c.field] && a.splice(i,1),p),objA);
console.log(arrayB);

How to change value of object which is inside an array using JavaScript or jQuery?

The code below comes from jQuery UI Autocomplete:
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
For example, I want to change the desc value of jquery-ui. How can I do that?
Additionally, is there a faster way to get the data? I mean give the object a name to fetch its data, just like the object inside an array? So it would be something like jquery-ui.jquery-ui.desc = ....
It is quite simple
Find the index of the object using findIndex method.
Store the index in variable.
Do a simple update like this: yourArray[indexThatyouFind]
//Initailize array of objects.
let myArray = [
{id: 0, name: "Jhon"},
{id: 1, name: "Sara"},
{id: 2, name: "Domnic"},
{id: 3, name: "Bravo"}
],
//Find index of specific object using findIndex method.
objIndex = myArray.findIndex((obj => obj.id == 1));
//Log object to Console.
console.log("Before update: ", myArray[objIndex])
//Update object's name property.
myArray[objIndex].name = "Laila"
//Log object to console again.
console.log("After update: ", myArray[objIndex])
You have to search in the array like:
function changeDesc( value, desc ) {
for (var i in projects) {
if (projects[i].value == value) {
projects[i].desc = desc;
break; //Stop this loop, we found it!
}
}
}
and use it like
var projects = [ ... ];
changeDesc ( 'jquery-ui', 'new description' );
UPDATE:
To get it faster:
var projects = {
jqueryUi : {
value: 'lol1',
desc: 'lol2'
}
};
projects.jqueryUi.desc = 'new string';
(In according to Frédéric's comment you shouldn't use hyphen in the object key, or you should use "jquery-ui" and projects["jquery-ui"] notation.)
The best solution, thanks to ES6.
This returns a new array with a replaced description for the object that contains a value equal to "jquery-ui".
const newProjects = projects.map(p =>
p.value === 'jquery-ui'
? { ...p, desc: 'new description' }
: p
);
Using map is the best solution without using extra libraries.(using ES6)
const state = [
{
userId: 1,
id: 100,
title: "delectus aut autem",
completed: false
},
{
userId: 1,
id: 101,
title: "quis ut nam facilis et officia qui",
completed: false
},
{
userId: 1,
id: 102,
title: "fugiat veniam minus",
completed: false
},
{
userId: 1,
id: 103,
title: "et porro tempora",
completed: true
}]
const newState = state.map(obj =>
obj.id === "101" ? { ...obj, completed: true } : obj
);
ES6 way, without mutating original data.
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
}];
//find the index of object from array that you want to update
const objIndex = projects.findIndex(obj => obj.value === 'jquery-ui');
// Make sure to avoid incorrect replacement
// When specific item is not found
if (objIndex === -1) {
return;
}
// make new object of updated object.
const updatedObj = { ...projects[objIndex], desc: 'updated desc value'};
// make final new array of objects by combining updated object.
const updatedProjects = [
...projects.slice(0, objIndex),
updatedObj,
...projects.slice(objIndex + 1),
];
console.log("original data=", projects);
console.log("updated data=", updatedProjects);
You can use $.each() to iterate over the array and locate the object you're interested in:
$.each(projects, function() {
if (this.value == "jquery-ui") {
this.desc = "Your new description";
}
});
given the following data, we want to replace berries in the summerFruits list with watermelon.
const summerFruits = [
{id:1,name:'apple'},
{id:2, name:'orange'},
{id:3, name: 'berries'}];
const fruit = {id:3, name: 'watermelon'};
Two ways you can do this.
First approach:
//create a copy of summer fruits.
const summerFruitsCopy = [...summerFruits];
//find index of item to be replaced
const targetIndex = summerFruits.findIndex(f=>f.id===3);
//replace the object with a new one.
summerFruitsCopy[targetIndex] = fruit;
Second approach: using map, and spread:
const summerFruitsCopy = summerFruits.map(fruitItem =>
fruitItem .id === fruit.id ?
{...summerFruits, ...fruit} : fruitItem );
summerFruitsCopy list will now return an array with updated object.
you can use .find so in your example
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
let project = projects.find((p) => {
return p.value === 'jquery-ui';
});
project.desc = 'your value'
It's easily can be accomplished with underscore/lodash library:
_.chain(projects)
.find({value:"jquery-ui"})
.merge({desc: "new desc"}).value();
Docs:
https://lodash.com/docs#find
https://lodash.com/docs#merge
you need to know the index of the object you are changing. then its pretty simple
projects[1].desc= "new string";
This is another answer involving find.
This relies on the fact that find:
iterates through every object in the array UNTIL a match is found
each object is provided to you and is MODIFIABLE
Here's the critical Javascript snippet:
projects.find( function (p) {
if (p.value !== 'jquery-ui') return false;
p.desc = 'your value';
return true;
} );
Here's an alternate version of the same Javascript:
projects.find( function (p) {
if (p.value === 'jquery-ui') {
p.desc = 'your value';
return true;
}
return false;
} );
Here's an even shorter (and somewhat more evil version):
projects.find( p => p.value === 'jquery-ui' && ( p.desc = 'your value', true ) );
Here's a full working version:
let projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
projects.find( p => p.value === 'jquery-ui' && ( p.desc = 'your value', true ) );
console.log( JSON.stringify( projects, undefined, 2 ) );
const users = [
{ name: "Alex", age: 25 },
{ name: "John", age: 32 },
];
const newUsers = users.map((user) => ({
...user,
age: user.age + 5, // just for example
}));
// newUsers = [
// {name:"Alex" , age:30},
// {name:"John , age:37}
// ]
I think this way is better
const index = projects.findIndex(project => project.value==='jquery-ui');
projects[index].desc = "updated desc";
const state = [
{
userId: 1,
id: 100,
title: "delectus aut autem",
completed: false
},
{
userId: 1,
id: 101,
title: "quis ut nam facilis et officia qui",
completed: false
},
{
userId: 1,
id: 102,
title: "fugiat veniam minus",
completed: false
},
{
userId: 1,
id: 103,
title: "et porro tempora",
completed: true
}]
const newState = state.map(obj =>
obj.id === "101" ? { ...obj, completed: true } : obj
);
Change value with conditions using for each loop
projects.forEach((p,index)=>{
if(index === 1){
p.value = "Updated jquery-ui"
}
})
// using higher-order functions to avoiding mutation
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
// using higher-order functions to avoiding mutation
index = projects.findIndex(x => x.value === 'jquery-ui');
[... projects.slice(0,index), {'x': 'xxxx'}, ...projects.slice(index + 1, projects.length)];
try using forEach(item,index) helper
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
let search_to_change = 'jquery'
projects.forEach((item,index)=>{
if(item.value == search_to_change )
projects[index].desc = 'your description '
})
let users = [
{id: 1, name: 'Benedict'},
{id: 2, name: 'Myles'},
{id: 3, name: 'Happy'},
]
users.map((user, index) => {
if(user.id === 1){
users[index] = {id: 1, name: 'Baba Benny'};
}
return user
})
console.log(users)
What this code does is map over the object and then match the desired
with if statement,
if(user.id === 1)
once there is match somewhere use its index to swap
users[index] = {id: 1, name: 'Baba Benny'};
the object in the array and then return the modified array
You can use map function --
const answers = this.state.answers.map(answer => {
if(answer.id === id) return { id: id, value: e.target.value }
return answer
})
this.setState({ answers: answers })
Here is a nice neat clear answer. I wasn't 100% sure this would work but it seems to be fine. Please let me know if a lib is required for this, but I don't think one is. Also if this doesn't work in x browser please let me know. I tried this in Chrome IE11 and Edge they all seemed to work fine.
var Students = [
{ ID: 1, FName: "Ajay", LName: "Test1", Age: 20},
{ ID: 2, FName: "Jack", LName: "Test2", Age: 21},
{ ID: 3, FName: "John", LName: "Test3", age: 22},
{ ID: 4, FName: "Steve", LName: "Test4", Age: 22}
]
Students.forEach(function (Student) {
if (Student.LName == 'Test1') {
Student.LName = 'Smith'
}
if (Student.LName == 'Test2') {
Student.LName = 'Black'
}
});
Students.forEach(function (Student) {
document.write(Student.FName + " " + Student.LName + "<BR>");
});
Output should be as follows
Ajay Smith
Jack Black
John Test3
Steve Test4
Assuming you wanted to run a bit more complicated codes during the modification, you might reach for an if-else statement over the ternary operator approach
// original 'projects' array;
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
// modify original 'projects' array, and save modified array into 'projects' variable
projects = projects.map(project => {
// When there's an object where key 'value' has value 'jquery-ui'
if (project.value == 'jquery-ui') {
// do stuff and set a new value for where object's key is 'value'
project.value = 'updated value';
// do more stuff and also set a new value for where the object's key is 'label', etc.
project.label = 'updated label';
// now return modified object
return project;
} else {
// just return object as is
return project;
}
});
// log modified 'projects' array
console.log(projects);
We can also use Array's map function to modify object of an array using Javascript.
function changeDesc(value, desc){
projects.map((project) => project.value == value ? project.desc = desc : null)
}
changeDesc('jquery', 'new description')
The power of javascript destructuring
const projects = [
{
value: 'jquery',
label: 'jQuery',
desc: 'the write less, do more, JavaScript library',
icon: 'jquery_32x32.png',
anotherObj: {
value: 'jquery',
label: 'jQuery',
desc: 'the write less, do more, JavaScript library',
icon: 'jquery_32x32.png',
},
},
{
value: 'jquery-ui',
label: 'jQuery UI',
desc: 'the official user interface library for jQuery',
icon: 'jqueryui_32x32.png',
},
{
value: 'sizzlejs',
label: 'Sizzle JS',
desc: 'a pure-JavaScript CSS selector engine',
icon: 'sizzlejs_32x32.png',
},
];
function createNewDate(date) {
const newDate = [];
date.map((obj, index) => {
if (index === 0) {
newDate.push({
...obj,
value: 'Jquery??',
label: 'Jquery is not that good',
anotherObj: {
...obj.anotherObj,
value: 'Javascript',
label: 'Javascript',
desc: 'Write more!!! do more!! with JavaScript',
icon: 'javascript_4kx4k.4kimage',
},
});
} else {
newDate.push({
...obj,
});
}
});
return newDate;
}
console.log(createNewDate(projects));
We can change in the following way
const oldArray = [{username: gopal, age: 20}, {username: gopi, age: 21}]
const obj = {username: gopal, age: 25}
const result = oldArray.map(d => d.username === 'gopi' ? d.age = obj.age : d)
Find the index first:
function getIndex(array, key, value) {
var found = false;
var i = 0;
while (i<array.length && !found) {
if (array[i][key]==value) {
found = true;
return i;
}
i++;
}
}
Then:
console.log(getIndex($scope.rides, "_id", id));
Then do what you want with this index, like:
$scope[returnedindex].someKey = "someValue";
Note: please do not use for, since for will check all the array documents, use while with a stopper, so it will stop once it is found, thus faster code.
Here i am using angular js. In javascript you can use for loop to find.
if($scope.bechval>0 &&$scope.bechval!=undefined)
{
angular.forEach($scope.model.benhmarkghamlest, function (val, key) {
$scope.model.benhmarkghamlest[key].bechval = $scope.bechval;
});
}
else {
alert("Please sepecify Bechmark value");
}
You can create your specific function like the below, then use that everywhere you need.
var each = (arr, func) =>
Array.from(
(function* (){
var i = 0;
for(var item of arr)
yield func(item, i++);
})()
);
Enjoy..
upsert(array, item) {
const i = array.findIndex(_item => _item.id === item.id);
if (i > -1) {
let result = array.filter(obj => obj.id !== item.id);
return [...result, item]
}
else {
return [...array, item]
};
}
The easiest way is to do this
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
}];
projects.find(data => data.value === "jquery").label ="xxxx"
console.log("------------>",projects)
to update multiple items with the matches use:
_.chain(projects).map(item => {
item.desc = item.value === "jquery-ui" ? "new desc" : item.desc;
return item;
})

Categories

Resources