How to convert particular key value from object to array javascript - javascript

I would like to know how to get particular key from object and convert to array
in javascript
var result = Object.entries(obj).includes(obj.name || obj.country || obj.account || obj.pincode).map(e=>e);
var obj = {
"name" : "Sen",
"country": "SG",
"key" : "Finance",
"city": "my",
"account":"saving",
"pincode":"1233"
}
Expected Output
["Sen", "SG", "saving", "1233"]

Create an array of requested keys, and then map it and take the values from the original object:
const obj = {"name":"Sen","country":"SG","key":"Finance","city":"my","account":"saving","pincode":"1233"}
const keys = ['name', 'country', 'account', 'pincode']
const result = keys.map(k => obj[k])
console.log(result) // ["Sen", "SG", "saving", "1233"]

I think you can try it like this.
There're other ways to get that result, too. Here's just a simple solution.
var obj = {
"name" : "Sen",
"country": "SG",
"key" : "Finance",
"city": "my",
"account":"saving",
"pincode":"1233"
}
let arrObj = []
let result = arrObj.push(obj.name, obj.country, obj.account, obj.pincode)
console.log(arrObj)

filter by a Set containing just the keys you want, then use map to return just the values:
const keys = new Set(['name', 'country', 'account', 'pincode'])
Object.entries(obj).filter(entry => keys.has(entry[0])).map(entry => entry[1])

If you want an array based on a known, hardcoded list of properties, the easiest option is an array literal:
const result = [obj.name, obj.country, obj.account, obj.pincode];
A benefit of this approach is that it guarantees the order of values in the array. While the order is predictable in your example (one onject literal), f your objs are created in different places, the order of the values may not always be the same.

var obj = {
"name" : "Sen",
"country": "SG",
"key" : "Finance",
"city": "my",
"account":"saving",
"pincode":"1233"
}
const Names = Object.keys(obj);
console.log(Names);
const Values = Object.values(obj);
console.log(Values);
const entries = Object.entries(obj);
console.log(entries);

Related

How to merge objects by value and change property type?

I have this array of objects
[ { "value": "1", "hobbies": 'netflix'},{ "value": "1", "hobbies": 'food'} ]
I want to:
Merge objects by value attribute
Change hobbies property to an array
Merge property values
The expected output
[ { "value": "1", "hobbies": ['netflix','food']}]
Using reduce comes in handy here as it helps you iterate over the array and keep an accumulator to store the data in each iteration.
I set the acc to be a JSON object (key-value pairs) where the key is the value attribute and the value is the resulting item with this value.
Along the way, if there is no item with the given key in the acc, we add the object as it is while setting hobbies as an array instead of a string.
Otherwise, if it does contain such an object, we add it's value to the existinghobbies list.
Finally, we take the values of the resulting object which gives the list of grouped objects.:
const arr = [
{ "value": "1", "hobbies": 'netflix'},
{ "value": "2", "hobbies": 'reading'},
{ "value": "1", "hobbies": 'food'},
];
const res = Object.values(
arr.reduce((acc,item) => {
const { value, hobbies } = item;
acc[value] = acc[value]
? { ...acc[value], hobbies: [...acc[value].hobbies, item.hobbies] }
: { ...item, hobbies: [hobbies] };
console.log(acc);
return acc;
}, {})
);
console.log(res);
You can use a forEach loop to iterate through the array.
var arr = [ { "value": "1", "hobbies": 'netflix'},{ "value": "1", "hobbies": 'food'} ];
var k = {};
var out = [];
arr.forEach(elm => {
if(typeof(k[elm.value]) == "undefined")
k[elm.value] = {value:elm.value, hobbies:[]};
k[elm.value].hobbies.push(elm.hobbies);
});
Object.keys(k).forEach(key => out.push(k[key]));
console.log(out);
You can use Array#reduce with an object to store the result for each value. On each iteration, if the current value does not exist as a key in the accumulator object, we create it and initialize the hobbies property as an empty array. Then, we add the current hobby to the object at that value. After the reduce operation, we use Object.values to get an array of all the resulting values.
const arr = [ { "value": "1", "hobbies": 'netflix'},{ "value": "1", "hobbies": 'food'} ];
const res = Object.values(
arr.reduce((acc,{value, hobbies})=>
((acc[value] = acc[value] || {value, hobbies: []}).hobbies.push(hobbies), acc),
{}));
console.log(res);

Convert Array into Object of Keys and Values using javascript/jquery [duplicate]

This question already has answers here:
Converting an Array to an Object
(3 answers)
Closed 2 years ago.
I am having troubles converting an array into an object of keys and values.
Currently, I have the following nested array:
var array = [[id1, parent1, "name1", "desc1"], [id2, parent1, "name2", "desc2"], [id3, parent1, "name3", "desc3"]];
Where the length of the array is dynamic.
For my code, I require the array to be converted such that it is an object of keys and values (consisting of the first (id) and third (name) value of each nested array).
For example, the object for the above array would be as follows:
var obj = {id1: name1, id2: name2, id3: name3};
Where the id values (id1, id2, id3) would be the corresponding integer values.
I apologise if a similar question has been asked before, but I couldn't seem to find a similar question which had a solution that worked for me.
Any help or advice would be greatly appreciated!
You can use a simple for loop to do it
var array = [
["id1", "parent1", "name1", "desc1"],
["id2", "parent1", "name2", "desc2"],
["id3", "parent1", "name3", "desc3"]
];
const obj = {}
for (const item of array) {
obj[item[0]] = item[2];
}
console.log(obj);
After using Array.map to extract the first and third entries from each element in the array, you can then use Object.fromEntries to convert the extracted array of key/value pairs into an object:
const [id1, id2, id3, parent1] = [1, 2, 3, 4];
const array = [
[id1, parent1, "name1", "desc1"],
[id2, parent1, "name2", "desc2"],
[id3, parent1, "name3", "desc3"]
];
const obj = Object.fromEntries(array.map(a => [a[0], a[2]]));
console.log(obj);
You basically want to convert your original array into an array of [key, value] pairs. You can then use the Object.fromEntries function to convert those key/values into an object. So, something like this:
const arr = [
["id1", "parent1", "name1", "desc1"],
["id2", "parent2", "name2", "desc2"],
["id3", "parent3", "name3", "desc3"],
];
const results = Object.fromEntries(arr.map(x => ([x[0], x[2]])))
console.log(results)
As a good practice, it is recommended to use let or const instead of var because var "pollute" the global namespace, so that's what my example will use.
However, if you need to use var, you can replace const with var inside my example and it will still be okay.
Given the following source array:
const array = [
[id1, parent1, "name1", "desc1"],
[id2, parent1, "name2", "desc2"],
[id3, parent1, "name3", "desc3"]
];
The following block of code create an object named obj using the 1st element of the sub-array as a key, and the 3rd element as the value:
// Create an empty object
const obj = {};
// Iterate through the source array
array.forEach((element) => {
// Assign the 1st element of the sub-array as the property key
// and the 3rd element as the property value
obj[element[0]] = element[2];
});
console.log(obj);
And this has the same effect, but simpler and with a smaller footprint:
const obj = Object.fromEntries(array.map(([key, _, value]) => [key, value]));
console.log(obj);

From an array of objects, extract properties into multiple arrays (one per property)?

I have a JSON array of objects in JS that look something like this:
"data": [
{"name": "abc", "location": "NY", "value": 1234, "potato": "tomato", "someOtherProp": "prop1"},
{"name": "def", "location": "CA", ... etc}
{etc ...},
]
I'm creating a UI for filtering down some of these fields and want to create an array for each attribute with all the given values in the data.
I know this is possible using something like this:
let result = objArray.map(a => a.name);
But using this strategy, I have to run map once for every property. Is there any way to only go through the array once but create a separate array for each? (Or is there a better way in general for creating filter options for a UI?)
To clarify, for the array above, I'd want an array for "names" (containing "abc" and "def"), an array for "locations" (containing NY, CA, etc.) an array for "potato"s and "someOtherProp".
I appreciate any help!
Thanks
Loop through the array with .reduce(). In each iteration, loop through the keys of the object using Object.keys(), adding any unique values to an array of the same name.
This solution eliminates duplicate entries and works with any amount of properties.
const data = [{name: "abc", location: "NY"},{name: "def", location: "CA"},{name: "xyz", location: "TX"},{name: "zyx", location: "TX"}];
const getFiltersFromData = (data) => {
return data.reduce((out,obj) => {
Object.keys(obj).forEach(k => {
if (out[k] === undefined) out[k] = [obj[k]]; //Array doesn't exist yet - instantiate it
else if (!out[k].includes(obj[k])) out[k].push(obj[k]); //Array exists and this value isn't in it - add the value to it
});
return out;
}, {});
};
const filters = getFiltersFromData(data);
console.log(filters.name);
console.log(filters.location);
.as-console-wrapper, .as-console { height: 100% !important; max-height: 100% !important; top: 0; }
You could create the separate arrays from names, locations and values and then use map on the data array to push each attribute value to the arrays. You can do that vs. running map multiple times for each property:
var names = [];
var locations = [];
var values = [];
data.map((elt) => {
names.push(elt.name);
locations.push(elt.location);
values.push(elt.value);
});
Try with Object.entries
You can get something like this:
const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]

Filter an array of objects by the length of the value of a string

want to filter an array of objects by array value of a key.
var data = [
{
"name": "Jim",
"age" : []
},
{
"name": "Jerry",
"age": [1,2]
}
];
var notEmpty = _.filter(data, ['age', null]);
would like to have the output of variable notEmpty return the object Jerry since the age array is not empty.
Without lodash it would be:
const notEmpty = data.filter(el => el.age.length);
Using vanilla javascript, this would give your desired result:
data.filter(x => x["age"].length > 0)

How can I get data iterate Json?

I need get data the my Json but I can't use 'key' because the 'key' is different each day.
I tried :
template: function(params) {
const objects = JSON.parse(JSON.stringify(params.data.masterdetail));
for (const obj of objects) {
const keys = Object.keys(obj);
const cont = 0;
keys.forEach(key => {
const valor = obj[key];
console.log('value ', valor[0]);
});
}
I first tried with 0 and then use cont, but with 0 console.log (value is undefined)....
If I use console.log ('value' , valor['name']) IT'S OK ! but I can't use keys and if I use valor[0] is undefined...........
Example Json
{
"headers": [
"headerName": "asdasd",
], //end headers
"datas": [
"idaam": "11",
"idorigen": "11",
"masterdetail": [{
"child1": {
"name": "I AM",
"age": "1"
},
"child2": {
"name": "YOU ARE",
"age": "2"
},
"child3": {
"name": "HE IS",
"age": "3"
},
}] //end masterdetail
]//end datas
}//end JSON
Edit :
I can't use 'keys' because today I receive "name", "typeval" etc. and tomorrow I can get 'surname','id' etc.
If you see in my first img you can see "4" bits of data.
1º obj[key]{
name = "adopt",
typeval= "",
etc
}
2º obj[key]{
"link" = "enlace",
"map" = "map"
etc
}
If I use this code : I get "name" OKEY but
I HAVE PROHIBITED use of value['name'] or value[typeval] because this Json always is dynamic.
var objects = params.data.masterdetail[0];
const keys = Object.keys(objects);
let value;
keys.forEach(key => {
value = objects[key];
console.log(value['name']);
console.log(value['typeval']);
});
I need for example :
var objects = params.data.masterdetail[0];
const keys = Object.keys(objects);
cont = 0 ;
keys.forEach(key => {
value = objects[key];
console.log(value[0]);
});
but value[0] is undefined and then when I arrive 2ºobj[key] link is index 0 but cont maybe is .... 4...
Sorry for my English...
To simply print the objects within the first entry in the masterdetail array, you can do the following:
var objects = params.datas.masterdetail[0];
const keys = Object.keys(objects);
keys.forEach(key => {
console.log('value ', objects[key]);
});
Based on a (suitably corrected - see my comments above) version of the JSON above, this would produce console output as follows:
value {name: "I AM", age: "1"}
value {name: "YOU ARE", age: "2"}
value {name: "HE IS", age: "3"}
Unfortunately it's not 100% clear from the question if this is the output you were looking for, but that's my best guess based on the code.
Your main mistakes were that
1) masterdetail is an array, and all the data is within the first element of that array, so to get the objects within it you need to select that element first. If the array can have multiple elements in real life then you'd need an outer loop around the code above to iterate through it.
2) If you're looping through the keys of an object, you don't need to also iterate through the properties a different way. You seemed to have two loops designed to do the same thing.

Categories

Resources