This is my json object:
{
id: 3,
cno: 103,
username: 'basha',
name: 'New Complaint',
desc: 'Need bag',
storeId: [ 5, 1 ]
}
I want my expected output like this:
[
{id: 3,cno: 103,username: 'basha',name: 'New Complaint',desc: 'Need bag',storeId:5},
{id: 3,cno: 103,username: 'basha',name: 'New Complaint',desc: 'Need bag',storeId:1}
]
You are right to choose .map. Issue is, you are trying to update an object and objects are passed using reference. So all the objects will hold same id. You will have to create a copy so that you do not override value. You can use Object.assign for that.
var data = {
id: 3,
cno: 103,
username: 'basha',
name: 'New Complaint',
desc: 'Need bag',
storeId: [ 5, 1 ]
};
var result = data.storeId.map(function(id){
return Object.assign({}, data, {storeId: id});
});
console.log(result)
If you are not comfortable using ES6 features, you can check following: How do I correctly clone a JavaScript object?
You can use .map() on the array storeId and return a new object which has current value as the value of storeId.
var obj = {
id: 3,
cno: 103,
username: 'basha',
name: 'New Complaint',
desc: 'Need bag',
storeId: [ 5, 1 ]
};
var data = obj.storeId.map(el => {
let newObject = Object.assign({}, obj);
newObject.storeId = el;
return newObject;
})
console.log(data);
You can use array#map with spread syntax to create an object with all the existing property and individual storeId.
var obj = {id: 3,cno: 103,username: 'basha',name: 'New Complaint',desc: 'Need bag',storeId: [ 5, 1 ]}
result = obj.storeId.map(storeId => ({...obj, storeId}) )
console.log(result);
var data = {
id: 3,
cno: 103,
username: 'basha',
name: 'New Complaint',
desc: 'Need bag',
storeId: [ 5, 1 ]
}
var finalData = data.storeId.map(x => {
return({
id: data.id,
cno: data.cno,
username: data.username,
name: data.name,
desc: data.desc,
storeId: x
})
});
console.log(finalData);
I tried this now i got this answer correctly, is this good approach?
Related
I have an array of objects that looks like this:
const arr = [
{id: 123, message: { user_id: 4, text: 'fish'}}
{id: 456, message: { user_id: 4, text: 'cow'}}
{id: 789, message: { user_id: 5, text: 'chicken'}}
{id: 010, message: { user_id: 5, text: 'turkey'}}
]
I want to return the first item in the array where the message.user_id is unique. I'm expecting a result like this:
newArr = [
{id: 123, message: { user_id: 4, text: 'fish'}}
{id: 789, message: { user_id: 5, text: 'chicken'}}
]
I can't seem to find any solution for this. I'm dealing with dynamic data so I can't exactly hardcode the user_id and the array I'm working with contains a lot of elements so I'm trying as much as possible to avoid looping through.
Please what's the best way for me to achieve this?
Here is another similar solution but with a bit modified syntax, I hope this will be helpful:
const arr = [
{id: 123, message: { user_id: 4, text: 'fish'}},
{id: 456, message: { user_id: 4, text: 'cow'}},
{id: 789, message: { user_id: 5, text: 'chicken'}},
{id: 010, message: { user_id: 5, text: 'turkey'}}
];
const uniqueResult = (Object.values(arr.reduce(function(acc, item) {
if (!acc[item.message.user_id]) {
acc[item.message.user_id] = item;
}
return acc;
}, {})));
console.log(uniqueResult);
Create a dictionary/object.
Iterate through the array and check if
the id is a key in it
2.1 If yes, skip
2.2 If not:
Add the row to the output
Add the user_id to the dictionary.
const arr = [
{id: 123, message: { user_id: 4, text: 'fish'}},
{id: 456, message: { user_id: 4, text: 'cow'}},
{id: 789, message: { user_id: 5, text: 'chicken'}},
{id: 010, message: { user_id: 5, text: 'turkey'}}
]
const userIDs = {}
const output = arr.reduce((acc, item) => {
const user_id = item.message.user_id
if (userIDs[user_id]) return acc
acc.push(item)
userIDs[user_id] = true;
return acc
},[])
console.log(output)
How to update the array by changing one of the objects?
This will be my array code
this.datas = [
{
index: 1,
name: 'Tony',
status: 'Absent',
reason: null
},
{
index: 2,
name: 'Chris',
status: 'Present',
reason: null
},
];
So now i want to write a function to update the reason like {reason: any reason} which from the index 1, index 2 remain the same.
So Far i had tried these
setReason = reason => {
let data = [...this.state.nameList];
let ind = data.findIndex(el => el.index === 'number');
data[ind] = { ...data[ind], reason: reason };
this.setState({
nameList: data
});
};
To update a single object data of an array
You need to first know the index of the object in the array which you want to update
eg Want to update first object of array
this.datas[0].reason = 'My custom reason';
Now you want to update the object of an array by finding the object in array you have to add a loop in it
eg: Update reason where name = Chris
for(i=0; i<this.datas.length; i++){
if(this.datas[i].name=='Chris'){
this.datas[i].reason = 'My custom reason';
break;
}
}
you can use map function on array.
let data = [
{
index: 1,
name: 'Tony',
status: 'Absent',
reason: null
},
{
index: 2,
name: 'Chris',
status: 'Present',
reason: null
},
];
data = data.map(obj=>{
return{
...obj,
reason: 'any reason',
}
})
You can use of in the for loop and update the property value in an array, this is the working solution of your question.
var datas = [
{
index: 1,
name: 'Tony',
status: 'Absent',
reason: null
},
{
index: 2,
name: 'Chris',
status: 'Present',
reason: null
},
];
for(data of datas){
data["reason"] = "any reason";
}
console.log(datas);
Try this
var datas = [
{
index: 1,
name: 'Tony',
status: 'Absent',
reason: null
},
{
index: 2,
name: 'Chris',
status: 'Present',
reason: null
},
];
datas.map(data=> data.reason ="my reason");
console.log(datas)
I have two array, lets suppose have below value of array: "
var array1 = [
{Id: "809cd136-02c7-4cc8-b9de-04fd3359b265", Name: "testing"},
{Id: "609d3a78-8f7c-4843-acdb-2dcfc73c0d96", Name: "Delhi"},
{Id: "264d54cb-b104-48ed-91db-673327ae8d0e", Name: "rohit-auditor"},
{Id: "ce9691b3-dc55-4d30-baf4-7987c2b49b3e", Name: "test"},
{Id: "284e9e98-8ed7-4fb7-b09f-5d1f2a668b15", Name: "aman"}
]
and second array is :
var array2 = ["809cd136-02c7-4cc8-b9de-04fd3359b265", "609d3a78-8f7c-4843-acdb-2dcfc73c0d96"]
Now i want to add one new key value in array1 only in those object whose value is equal to array one. In other words in want to match both array and want to add "status = true" in those that is having equal value.
new key want to add is :
{status: true}
Now my new array should be:
[
{Id: "809cd136-02c7-4cc8-b9de-04fd3359b265", Name: "testing", status: true},
{Id: "609d3a78-8f7c-4843-acdb-2dcfc73c0d96", Name: "Delhi", status: true},
{Id: "264d54cb-b104-48ed-91db-673327ae8d0e", Name: "rohit-auditor"},
{Id: "ce9691b3-dc55-4d30-baf4-7987c2b49b3e", Name: "test"},
{Id: "284e9e98-8ed7-4fb7-b09f-5d1f2a668b15", Name: "aman"}
]
Hope you understand.
Thanks in advance,
You could use forEach and find like this:
let array1=[{Id:"809cd136-02c7-4cc8-b9de-04fd3359b265",Name:"testing"},{Id:"609d3a78-8f7c-4843-acdb-2dcfc73c0d96",Name:"Delhi"},{Id:"264d54cb-b104-48ed-91db-673327ae8d0e",Name:"rohit-auditor"},{Id:"ce9691b3-dc55-4d30-baf4-7987c2b49b3e",Name:"test"},{Id:"284e9e98-8ed7-4fb7-b09f-5d1f2a668b15",Name:"aman"}],
array2=["809cd136-02c7-4cc8-b9de-04fd3359b265","609d3a78-8f7c-4843-acdb-2dcfc73c0d96"]
array2.forEach(id => {
let found = array1.find(a => a.Id === id);
if(found)
found.status = true
})
console.log(array1)
The if check is there to check if the Id in array2 exists in array1. If every Id in array2 exists in array1, you can simply change it to:
array1.find(a => a.Id === id).status = true
You can use Array#map method to iterate and create a new array and then use Array#includes method to check the value present in the array2. Where use ES6 spread syntax to combine both objects.
var newArray = array1.map(o => array2.includes(o.Id) ? {...o, ...add} : { ...add })
var array1 = [{
Id: "809cd136-02c7-4cc8-b9de-04fd3359b265",
Name: "testing"
},
{
Id: "609d3a78-8f7c-4843-acdb-2dcfc`Array#forEach`73c0d96",
Name: "Delhi"
},
{
Id: "264d54cb-b104-48ed-91db-673327ae8d0e",
Name: "rohit-auditor"
},
{
Id: "ce9691b3-dc55-4d30-baf4-7987c2b49b3e",
Name: "test"
},
{
Id: "284e9e98-8ed7-4fb7-b09f-5d1f2a668b15",
Name: "aman"
}
]
var array2 = ["809cd136-02c7-4cc8-b9de-04fd3359b265", "609d3a78-8f7c-4843-acdb-2dcfc73c0d96"]
var add = {
status: true
};
var newArray = array1.map(o => array2.includes(o.Id) ? {...o, ...add} : { ...add })
console.log(newArray);
If you want to update the original array then simply iterate over the array using Array#forEach method and add an additional property using Object.assign if necessary.
array1.forEach(o => array2.includes(o.Id) && Object.assign(o,add))
var array1 = [{
Id: "809cd136-02c7-4cc8-b9de-04fd3359b265",
Name: "testing"
},
{
Id: "609d3a78-8f7c-4843-acdb-2dcfc73c0d96",
Name: "Delhi"
},
{
Id: "264d54cb-b104-48ed-91db-673327ae8d0e",
Name: "rohit-auditor"
},
{
Id: "ce9691b3-dc55-4d30-baf4-7987c2b49b3e",
Name: "test"
},
{
Id: "284e9e98-8ed7-4fb7-b09f-5d1f2a668b15",
Name: "aman"
}
]
var array2 = ["809cd136-02c7-4cc8-b9de-04fd3359b265", "609d3a78-8f7c-4843-acdb-2dcfc73c0d96"]
var add = {
status: true
};
array1.forEach(o => array2.includes(o.Id) && Object.assign(o, add))
console.log(array1);
A simple map & indexOf will be enough
var array1 = [
{Id: "809cd136-02c7-4cc8-b9de-04fd3359b265", Name: "testing"},
{Id: "609d3a78-8f7c-4843-acdb-2dcfc73c0d96", Name: "Delhi"},
{Id: "264d54cb-b104-48ed-91db-673327ae8d0e", Name: "rohit-auditor"},
{Id: "ce9691b3-dc55-4d30-baf4-7987c2b49b3e", Name: "test"},
{Id: "284e9e98-8ed7-4fb7-b09f-5d1f2a668b15", Name: "aman"}
]
var array2 = ["809cd136-02c7-4cc8-b9de-04fd3359b265", "609d3a78-8f7c-4843-acdb-2dcfc73c0d96"]
var result=array1.map(el=>{
if(array2.indexOf(el.Id)>-1){
el.status=true
}
return el
})
You have to compare element of second array with id's of element of first array and add key (status) to those matching found.
var array1 = [{Id: "809cd136-02c7-4cc8-b9de-04fd3359b265",Name: "testing"},{Id: "609d3a78-8f7c-4843-acdb-2dcfc73c0d96", Name: "Delhi"},{Id: "264d54cb-b104-48ed-91db-673327ae8d0e", Name: "rohit-auditor"},{Id: "ce9691b3-dc55-4d30-baf4-7987c2b49b3e", Name: "test"},{Id: "284e9e98-8ed7-4fb7-b09f-5d1f2a668b15", Name: "aman"}];
var array2 = ["809cd136-02c7-4cc8-b9de-04fd3359b265", "609d3a78-8f7c-4843-acdb-2dcfc73c0d96"];
array2.forEach(function(secondElem) {
let matchingElemInFirstArr = array1.find(el=>el.Id==secondElem);
matchingElemInFirstArr ['status']=true;
});
console.log(array1);
var data = [{
id: 22,
cno: 1,
username: 'white',
name: 'New Complaint',
stype: null,
cname: 'ff',
product: 'ff',
}];
var finalData = data.map(x => {
return ({ cno: x.cno + 1 })
});
console.log(finalData); // output [ { cno: 2} ]
My expected output i need this as object not as Array, is it possible to do using map?
Finally i need { cno : 2}
Since you're just trying to operate on a single object you shouldn't use map at all. You should use something like:
var finalData = { cno: data[ 0 ].cno + 1 };
Example:
var data = [{
id: 22,
cno: 1,
username: 'white',
name: 'New Complaint',
stype: null,
cname: 'ff',
product: 'ff',
}];
var finalData = { cno: data[ 0 ].cno + 1 };
console.log( finalData );
you can use reduce instead of map. map actually return an array. using reduce you can get the desired result.
var data = [{
id: 22,
cno: 1,
username: 'white',
name: 'New Complaint',
stype: null,
cname: 'ff',
product: 'ff',
}];
var finalData = data.reduce((acc, elem, index) => {
acc.cno = elem.cno + 1
return acc
}, {});
console.log(finalData); // output { cno: 2}
The simplest approach is using ES6 destructuring ([data] = data;) as in the following example:
var data = [{
id: 22,
cno: 1,
username: 'white',
name: 'New Complaint',
stype: null,
cname: 'ff',
product: 'ff',
}];
[data] = data; // data is now the nested object
console.log(data); // Return data as object
// After that, you can modify data however you want
data.cno += 1;
console.log(data); // Return updated data as object
I have my original objects as follow. All I need is to just extract few properties from existing one and create new object.
var data = [{
id: 3,
name: Axe,
location: alkt
}, {
id: 5,
name: Roy,
location: grelad
}]
I need my output as,
var data_new = [{
id: 3,
name: Axe
}, {
id: 5,
name: Roy,
}]
How to implement in underscore js or any simple method. Possible its a large JSON object.
If there are just few properties you want to extract then simple Array.prototype.map will works fine:
var data = [{
id: 3,
name: 'Axe',
location: 'alkt'
}, {
id: 5,
name: 'Roy',
location: 'grelad'
}]
var result = data.map(function(obj) {
return {
id: obj.id,
name: obj.name
};
});
alert(JSON.stringify(result, null, 4));
Use pick in undescorejs http://underscorejs.org/#pick
Or omit http://underscorejs.org/#omit
_.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');
=> {name: 'moe', age: 50}
_.pick({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
return _.isNumber(value);
});
=> {age: 50}
It you want remove each item's location
var data_new = _.map(data, function(item) {
return _.omit(item, 'location');
});
If all you want is remove properties from objects in an array, you could just delete them while iterating with forEach:
var data_new = data;
data_new.forEach(function(obj){ delete obj.location; /* or any other */ });
$scope.data_new = [];
for(i in $scope.data){
$scope.data_new.push(
{ id: $scope.data[i].id, name: $scope.data[i].name }
)
}