I am having a array of objects which looks like this
var data = [
{
"id": "K014-s1",
"status": true,
"amount": 992,
"check": true,
},
{
"id": "K014-s2",
"status": false,
"amount": 10992,
"check": true,
}
]
I want only certain key values from the object in the array
Required Output:
var data = [
{
"id": "K014-s1",
"amount": 992,
},
{
"id": "K014-s2",
"amount": 10992,
}
]
Code I tried:
var filteredData = []
var result = data.map((obj) => {
filteredData.push(obj.id)
})
console.log(filteredData)
I tried. But don't Know how to make it. Please Help me with some solutions
instead of pushing object to another array,you can simply map your data like this
var result = data.map((obj) => {
return {
id:obj.id,
amount:obj.amount
}
})
Array.prototype.map already creates a new array, so result will already be the new value you are looking for.
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
var filteredResult = data.map((obj) => {
//additional logic, if needed here.
return {
id: obj.id,
amount: ob.amount,
}
})
Alternatively you can of course use a for loop or array.prototype.forEach to achieve the same:
var filteredData = []
data.forEach((obj) => {
filteredData.push({
id: obj.id,
amount: ob.amount,
})
})
No need to initiate a new array because the map method returns a new array what you can do is map the array then delete the property or method that you want then return the new array. Here's a simple solution that you use for your reference
const filteredData = data.map(newData => {
delete newData.status
delete newData.check
return newData
})
Simply you can loop over array using forEach method and delete key, value pairs. For example data.forEach((obj) => { delete obj.status; delete obj.check; }) since array is a reference type you can easily mutate it and not create a duplicate of data.
Related
I have an Array of Objects. Every object in this Array has some Keypairs. One of this Keypairs ("obj", for example) is an Array of Objects too.
Example what I have:
const arrOfObj = [
{
"id": 1
"obj": {
"arr1": ["arr1-1"],
"arr2": ["arr2-1", "arr2-2"],
"arr3": ["arr3-1", "arr3-2"]
}
},
{
"id": 1
"obj": {
"arr1": ["arr1-2"],
"arr2": ["arr2-1", "arr2-3"],
"arr3": ["arr3-1", "arr3-3"],
"arr4": ["arr4-1"],
}
},
];
I need to get new Object of "obj" Objects with unique keys and unique elements inside them.
Example what I need:
const newObj = {
"arr1": ["arr1-1", "arr1-2"],
"arr2": ["arr2-1", "arr2-2", "arr2-3"],
"arr3": ["arr3-1", "arr3-2", "arr3-3"],
"arr4": ["arr4-1"],
}
All of this comes dynamically from API by request, so I don`t know the names of this keypairs, but i need to store them.
I have Solution, but I`m new in JavaScript, and want to know how to simplify and improve my poor Code.
1. First, I`m defining the new Object and retrieving the Names for his keypairs from "arrOfObj".
let filterObj = {};
arrOfObj.forEach(function (item) {
for (let key in item.obj) {
filterObj[key] = [];
}
});
2. After that I`m getting all the Elements of every Array from "arrOfObj" and store them in new Object "filterObj" in the Keypair with the same Name.
arrOfObj.forEach(function (item) {
for (let key in item.obj) {
for (let element = 0; element < item.obj[key].length; element++) {
filterObj[key].push(item.obj[key][element]);
}
}
});
3. To the end I`m filtering Arrays to get unique Elements only.
for (let key in filterObj) {
filterObj[key] = Array.from(new Set(filterObj[key]));
}
It works, I`ve got what I want, but it seems to much monstrously. How this code can be simplified the best way?
Thanks for the help and advices.
You can use some destructuring and Object.entries() and Object.keys() to streamline this and do everything to the new Object only
const newObj = {}
arrOfObj.forEach(({obj}) => {
Object.entries(obj).forEach(([k, arr]) => {
newObj[k] = newObj[k] || [];
newObj[k].push(...arr);
})
});
Object.keys(newObj).forEach(k => newObj[k] = [...new Set(newObj[k])]);
console.log(newObj)
<script>
const arrOfObj=[{id:1,obj:{arr1:["arr1-1"],arr2:["arr2-1","arr2-2"],arr3:["arr3-1","arr3-2"]}},{id:1,obj:{arr1:["arr1-2"],arr2:["arr2-1","arr2-3"],arr3:["arr3-1","arr3-3"],arr4:["arr4-1"]}}];
</script>
Another solution using Object#fromEntries, Array#reduce, Object#entries, Array#forEach, Set, and Map:
const arrOfObj = [ { "id": 1, "obj": { "arr1": ["arr1-1"], "arr2": ["arr2-1", "arr2-2"], "arr3": ["arr3-1", "arr3-2"] } }, { "id": 1, "obj": { "arr1": ["arr1-2"], "arr2": ["arr2-1", "arr2-3"], "arr3": ["arr3-1", "arr3-3"], "arr4": ["arr4-1"] } } ];
const filterObj =
// transform the resulting list of key-values pairs to an object at the end
Object.fromEntries(
// get a map of array name as key and its unique items as value
[...arrOfObj.reduce((map, { obj = {} }) => {
// iterate over current element's object to update the map
Object.entries(obj).forEach(([currentKey, currentValues]) => {
const keyValues = [...(map.get(currentKey) || []), ...currentValues];
map.set(currentKey, [...new Set(keyValues)]);
});
return map;
}, new Map)]
);
console.log(filterObj);
I am new to react. Here I have an object which has array (Map)
"POSSIBLE_UPDATE_OPTIONS": {
"Process": ["confirm"],
"Confirmed": [
"Process",
"Validated"
],
"Validated": [
"Process",
"Sent"
],
"Sent": []
}
Now, Here current status value is process. Now, if it is process it should return the ['confirm'] array. these are the possible option for this change.
Now, I have written one function for this .
const validate = (currentstatus) => {
let possibleOptions =
config?.appConfig?.?.POSSIBLE_UPDATE_OPTIONS_MAP?.[
data
] ?? []
return possibleoptions
}
This will return me the array .Now, I have to convert this array element into an object in the
lets say I have got the ["confirm"] as return .
Now, object would be like
[{
"label": "confirm",
"value": "VIP:confirm"
}]
SO, here need to add VIP: in the value key.
So, this function should return me an array of object in this format.
Can any one help me with this ?
You can use map function.
Like this
const validate = (currentstatus) => {
let possibleOptions =
config?.appConfig?.?.POSSIBLE_UPDATE_OPTIONS_MAP?.[
data
] ?? []
return possibleoptions.map(item => ({label: `${item}`, value: `VIP:${item}`}))
}
I'm new in Vue js, and I have data in array object like below when I use vue-multiselect.
[
{
"id": 1,
"add_on_type": "Xtra",
"name": "test",
"price": 12,
"created_at": "2020-06-25 10:12:43",
"updated_at": "2020-06-25 10:12:43"
},
{
"id": 3,
"add_on_type": "Xtra",
"name": "Some x",
"price": 120,
"created_at": "2020-06-30 05:47:52",
"updated_at": "2020-06-30 05:47:52"
}
]
but in my function I need to access like key:value like below
"xtra": {
// key: value
0: 1
1: 3
}
but I get all array object instead of id only. I need to get the ID only in array, below is my code. I don't know how to get only id from array using below code.
this.$axios
.get("items/" + this.item)
.then(res => {
// below line is how I get the array object, but I need only id in array.
data.xtra = this.extra;
console.log(data);
})
.catch(err => {
throw err;
});
this maybe easy for some people, but I cannot find the way to to do. any help would be appreciated. thanks in advance
If I understood correctly your question, this.item is holding an object retrieved from the array. If is like this, it should be as easy as:
.get("items/" + this.item.id)
if you want to create new array you can do this at your return from axios
.then(res => {
let arr = res.data
this.xtra = arr.map(x =>
x.item.id)
})
First declare Items as reactive array in setup function
const tools = reactive([]);
Then in methods, retrieve
axios.get("/user-items").then(response => {
var items = [];
response.data.forEach((item, index) => {
items.push(item.id);
})
Object.assign(this.items, items);
});
So I am pretty new when it comes to Javascript and it is as simple as read a json list with a value of:
{
"URL": [{
"https://testing.com/en/p/-12332423/": "999"
}, {
"https://testing.com/en/p/-123456/": "123"
},
{
"https://testing.com/en/p/-456436346/": "422"
}
]
}
What I would like to do is to have both the URL and the amount of numbers etc
"https://testing.com/en/p/-12332423/" and "999"
and I would like to for loop so it runs each "site" one by one so the first loop should be
"https://testing.com/en/p/-12332423/" and "999"
second loop should be:
"https://testing.com/en/p/-123456/" and "123"
and so on depending on whats inside the json basically.
So my question is how am I able to loop it so I can use those values for each loop?
As Adam Orlov pointed out in the coment, Object.entries() can be very useful here.
const URLobj = {
"URL": [{
"https://testing.com/en/p/-12332423/": "999"
}, {
"https://testing.com/en/p/-123456/": "123"
},
{
"https://testing.com/en/p/-456436346/": "422"
}
]
};
URLobj.URL.forEach(ob => {
console.log('ob', ob);
const entries = Object.entries(ob)[0]; // 0 just means the first key-value pair, but because each object has only one we can just use the first one
const url = entries[0];
const number = entries[1];
console.log('url', url);
console.log('number', number);
})
You mean something like this using Object.entries
const data = {
"URL": [
{"https://testing.com/en/p/-12332423/": "999"},
{"https://testing.com/en/p/-123456/": "123"},
{"https://testing.com/en/p/-456436346/": "422"}
]
}
data.URL.forEach(obj => { // loop
const [url, num] = Object.entries(obj)[0]; // grab the key and value from each entry - note the [0]
console.log("Url",url,"Number", num); // do something with them
})
let's call your object o1 for simplicity. So you can really go to town with this link - https://zellwk.com/blog/looping-through-js-objects/
or you can just use this code :
for(var i = 0; i < o1.URL.length; i++) {
//each entry
var site = Object.keys(URL[i]) [0];
var value = Object.values(URL[i]) [0];
// ... do whatever
}
don't forget each member of the array is an object (key : value) in its own right
You can extract the keys and their values into another object array using map
Then use the for loop on the newly created array. You can use this method on any object to separate their keys and values into another object array.
const data = {
"URL": [{
"https://testing.com/en/p/-12332423/": "999"
}, {
"https://testing.com/en/p/-123456/": "123"
},
{
"https://testing.com/en/p/-456436346/": "422"
}
]
}
var extracted = data.URL.map(e => ({
url: Object.keys(e)[0],
number: Object.values(e)[0]
}))
extracted.forEach((e) => console.log(e))
I need to push a new ID for my data array. If I try pushing into data it creates one more object but not adding into the array for each.
Data:
[{"devices":{"dID":"TLSM01"},"uuid":"e863c776-f939-4761-bbce-bf0501b42ef7"},
{"devices":{"dID":"TLSM01"},"uuid":"5a0cd70d-891d-48d8-b205-e92e828ac445"}]
Data need to be added:
{"EntityID":"12458412548"}
Final Result:
[{"devices":{"dID":"TLSM01","EntityID":"12458412548"},"uuid":"e863c776-f939-4761-bbce-bf0501b42ef7"},
{"devices":{"dID":"TLSM01","EntityID":"12458412548"},"uuid":"5a0cd70d-891d-48d8-b205-e92e828ac445"}]
Code:
var data = [{
"devices": {
"dID": "TLSM01"
},
"uuid": "e863c776-f939-4761-bbce-bf0501b42ef7"
}, {
"devices": {
"dID": "TLSM01"
},
"uuid": "5a0cd70d-891d-48d8-b205-e92e828ac445"
}]
data.push({
"EntityID": "test"
});
console.log(data);
data is an array containing objects. If you want to add a property to each object you have to iterate over the array.
You need to add a new property to the object devices which is not an array thus you cannot use .push()
var data = [{"devices":{"dID":"TLSM01"},"uuid":"e863c776-f939-4761-bbce-bf0501b42ef7"},{"devices":{"dID":"TLSM01"},"uuid":"5a0cd70d-891d-48d8-b205-e92e828ac445"}];
data.forEach(d=>d.devices['EntityID']="test");
console.log(data);
If your "final result" is the result you want to achieve, you don't want to push anything. You're just setting a new property on the entries that already exist in the array. So, loop through and do that:
data.forEach(function(entry) {
entry.EntityID = "12458412548";
});
(Or a simple for loop.)
If you're using ES2015+ syntax, you could use an arrow function:
data.forEach(entry => entry.EntityID = "12458412548");
...or a for-of loop:
for (const entry of data) {
entry.EntityID = "12458412548";
}
DEMO
var jsonObj = [{"devices":{"dID":"TLSM01"},"uuid":"e863c776-f939-4761-bbce-bf0501b42ef7"},
{"devices":{"dID":"TLSM01"},"uuid":"5a0cd70d-891d-48d8-b205-e92e828ac445"}];
jsonObj.map(item => item.devices["EntityID"] = "12458412548");
console.log(jsonObj);