I have an existing JSON object that looks like so:
var data = {ID: 123, Name: "test"}
Now I want to add in an extra property and value to data based on the condition of an inline if statement. The result should look like the following:
data = {ID: 123, Name: "test", Surname: "again"}
The object above is based on the true condition, while the object below is based on the false condition:
data = {ID: 123, Name: "test", Lastname: "again"}
Note the change of the property name from Surname to Lastname.
So my question is, how do I add the new property and value into object based on the inline if condition?
I tried the following but obviously that did not work:
var data = {ID: 123, Name: "test"};
data = params.Region == 1 ? data.Surname = "again" : data.Lastname = "again"
Any help please
data[params.Region == 1 ? 'Surname' : 'Lastname'] = "again"
params.Region == 1 ? data.Surname = "again" : data.Lastname = "again"
You are assigning params.Region the value 1. Typo!
data = (params.Region === 1) ? data.Surname = "again" : data.Lastname = "again"
Related
I have an object array
const arr =
[
{ id: 1, name : "Joe", age:20, email: "joe#hotmail.com"},
{ id: 2, name : "Mike", age:50, email: "mike#hotmail.com"},
{ id: 3, name : "Joe", age:45, email: "harry#hotmail.com"}
]
How can I create a new array without modifying first one with only one property changed, like this (id is unique):
[
{ id: 1, name : "Joe", age:20, email: "joe#hotmail.com"},
{ id: 2, name : "Mike", age:50, email: "mike#hotmail.com"},
{ id: 3, name : "Harry", age:45, email: "harry#hotmail.com"}
]
Changed last element name property from "Joe" to "Harry"
Below I have created a sample snippet which clones the array of objects and modifies only the name of the object where id = 3.
const arr = [{id:1,name:"Joe",age:20,email:"joe#hotmail.com"},{id:2,name:"Mike",age:50,email:"mike#hotmail.com"},{id:3,name:"Joe",age:45,email:"harry#hotmail.com"}]
const cloneAndModify = (data) => {
return data.map(d => ({
...d,
...(d.id === 3 && {
name: "Harry"
})
}))
}
console.log("Original Array: ", arr);
console.log("Cloned Array: ", cloneAndModify(arr))
.as-console-wrapper {
max-height: 100% !important;
}
You can replace d.id === 3 condition as per your actual requirement based on which you want to change the name.
You would first need to clone the array either manually or using a library function like lodash._cloneDeep (https://www.npmjs.com/package/lodash.clonedeep).
If you want to do it manually, just loop over each property of the array elements and copy that into a new array.
After that you can change the cloned array however you like and it will not affect the original one.
I have this array "Group":
i would like to have the value of name (test01) but i have undefined with console.log(group['name']), console.log(group[name]) or console.log(group.name).
How i can display the value ?
Thanks
It's an array of objects - access the specific object first using group[0] then access the property you want with group[0].name.
const group = [{ name: "test01" }];
const res = group[0].name;
console.log(res);
Based on what you have you can call your propriety if it's an object or an array of objects.
const object = {
name: "test1",
group: "c2"
}
console.log(object.name)
const array = [{
name: "test1",
group: "c2"
}]
console.log(array[0].name)
I am using this.state.student in react to display (name,school,class.etc)..
how i change the "school" display to "college" without replacing the value of "School" in the api..
as i am new to code i tried
'var student = [ {"name", "school", "class"}];'
'student[1] = "college";'
but this just replaces the value. i just want to change the display
of "school" please help
Check my code. I created a function addToArray that will accept a parameter of object then it will add it to the students array. This will give you an output of [{ name: "John Doe", school: "College", class: "A" }]
let students = [];
addToArray = student => {
students.push({
name: student.name,
school: student.school,
class: student.class
});
console.log(students);
};
this.addToArray({
name: "John Doe",
school: "College",
class: "A"
});
Use this to create an array of objects with different key and value pair,
var productArr = [];
productId = 1;
productName = 'Product Name';
productArr.push({ id: productId, name: productName });
Hope it'll work for you. Waiting for your response. Thank you!
You can try this:
var student = [ {"name": "school", "class":"XYZ"}];
student = [...student,{"name":"college","class":"ABC"}]
console.log(student)
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)
})
I have a drop down menu which lists out groups. Each group contains a property (boolean) that determines if the groups owner is a user or another group
If the groups owner is a user, I get the groups ownerID and compare that with an array of users to determine which user matches that ID and set that user as the selectedOwner. However, if the groups owner is a group, I'll try to loop through all my groups to find the match and set that group as selectedOwner
This is my controller function:
$scope.groupOwner = function (){
var temp = $scope.selectedGroup.ownerIsUser ? $scope.users : $scope.groups;
var index = temp.length;
console.dir(temp);
while(index--){
if($scope.selectedGroup.owner === temp[index].id){
$scope.selectedOwner = temp[index];
console.log($scope.selectedOwner);
break;
};
};
};
Whenever the dropdown is changed it called groupOwner which checked the selectedUser.ownerIsUser property to determine which array I should be looking into, users or groups.
However, the temp variable is always returning true, no matter what the selectedGroup owner property is set to.
This is what the objects look like:
User = {
name: Demo Administrator,
id: 90,
domain: i:0#.w|itun\demoadmin_compulite,
email: ,
isAdmin: False
}
selectedGroup = {
name: Test Group,
id: 10,
description: ,
owner: 88,
ownerIsUser: False
}
HTML:
<div class="topRow">
<label for="entityDropDown">Select a Group:</label>
<select id="entityDropDown" ng-model="selectedGroup" ng-options="group as group.name for group in groups" ng-change="getGroupInfo(selectedGroup)"></select>
<div class="delGroupBtn"><a>✖</a>
</div>
</div>
Console output of object:
Object {name: "Test Group 4", id: "117", description: "", owner: "71", ownerIsUser: "False"…}
description: ""
id: "117"
name: "Test Group 4"
owner: "71"
ownerIsUser: "False"
__proto__: Object
Solved:
$scope.groupOwner = function (){
//object stores string not booleans
var isUser = $scope.selectedGroup.ownerIsUser === "True"? true : false;
var owner = isUser ? $scope.user : $scope.group;
var index = owner.length;
console.dir(owner);
while(index--){
if($scope.selectedGroup.owner === owner[index].id){
$scope.selectedOwner = owner[index];
console.log($scope.selectedOwner);
break;
};
};
};
Your variable is "False" and not boolean false."False" is a string, which always evaluates as true.
var temp = $scope.selectedGroup.ownerIsUser ? $scope.users : $scope.groups;
Will always set temp = $scope.users
Some javascript console testing example :
> a = "False"
> "False"
> b = false
> false
> testValue = a ? 1 : 2;
> 1
> testValue = b ? 1 : 2;
2
this object is not defined currectly
selectedGroup: {
name: Test Group,
id: 10,
description: ,
owner: 88,
ownerIsUser: False
}
It should be defined with all variable values
selectedGroup: {
name: Test_Group, // or 'Test Group'
id: 10,
description: '',
owner: 88,
ownerIsUser: false
}