I need to get an array of all the name values from a JSON structure.
My JSON looks like this:
{
"profile": {
"G5j7": {
"name": "siddharth",
"age": "17"
},
"Loj9": {
"name": "ram",
"age": "20"
},
"Huy8": {
"name": "maix"
}
}
}
I can get a specific name value by:
var singleName = profile.G5j7.name;
But how do I get an array of all the name values if don't know all the IDs inside profile? I need to store in a variable.
const arrayName = Object.values(profile).map((item) => item.name);
You can use Object.getOwnPropertyNames. This function getting field names from in object to array.
let data = { "profile": { "G5j7": { "name": "siddharth", "age": "17" }, "Loj9": { "name": "ram", "age": "20" }, "Huy8": { "name": "maix" } } }
let propNames = Object.getOwnPropertyNames(data.profile)
propNames.forEach((propname) => { console.log(data.profile[propname].name) })
Object.values(yourObj.profile).map(v => v.name)
Object.values() returns an array of the values on every (own) prop of your object. So you can forget about the property names and iterate on its values
You can use Object.keys to get all properties keys in an Object, with that you can get access to all profile object keys with that you can retrieve name for each key like bellow
let data = {
"profile": {
"G5j7": {
"name": "siddharth",
"age": "17"
},
"Loj9": {
"name": "ram",
"age": "20"
},
"Huy8": {
"name": "maix"
}
}
};
let profiles_keys = Object.keys(data.profile);
let results = profiles_keys.reduce((accumulator, current)=> {
return accumulator.concat(data.profile[current].name)
}, []);
console.log(results);
let data = {
"profile":
{ "G5j7": { "name": "siddharth", "age": "17" },
"Loj9": { "name": "ram", "age": "20" },
"Huy8": { "name": "maix" }
}
};
for (const [key, value] of Object.entries(data.profile)) {
console.log(`${value.name}`);
}
You can do like this:
const names = Object.values(profile).map((profile) => profile.name);
Object.values() returns an array of the values.
Then for each profile, use .map() to get each name.
const decodedJsonObject = " { "profile": { "G5j7": { "name": "siddharth", "age": "17" }, "Loj9": { "name": "ram", "age": "20" }, "Huy8": { "name": "maix" } } }"
var singleName = profile.G5j7.name;
Related
I have an array of objects:
const data = [{
"Name": "Mike",
"Age": "24",
"debt": "1000"
},
{
"Name": "Mike",
"Age": "24",
"debt": "2000"
},
{
"Name": "Nathan",
"Age": "26",
"debt": "500"
},
]
How do I create an array of objects based on unique values of Name and Including sum of all debts assigned with that name?
For example:
const newData= [{
"Name": "Mike",
"Age": "24",
"debt": "3000"
},
{
"Name": "Nathan",
"Age": "26",
"debt": "500"
},
]
I have tried several ways, among which I first get unique data based on name:
//Original data
const data = [{
"Name": "Mike",
"Age": "24",
"debt": "1000"
},
{
"Name": "Mike",
"Age": "24",
"debt": "2000"
},
{
"Name": "Nathan",
"Age": "26",
"debt": "500"
},
]
//getting unique values based on name
const unique = [...new Set(data.map(item => item.Name))]
//mapping and adding each name into saperate object and later //combining it using Object.merge after adding new Debt which //contains sum of both the debts
for (value in unique) {
var datamenu = data.map(function(element, index, array) {
if (element.Instrument === value) {
unique[value] = element
}
return unique[value]
})
}
console.log(datamenu)
But I only get output of Nathan in place of mike too.
I've found your solution. Try this:
const getData = () => {
const debtSums = data.map(person => {
const personD = data.filter(el => el.Name === person.Name).reduce((prev, curr) => {
const debt = prev.debt + curr.debt;
return {...person, debt};
})
return personD;
})
const removeDuplicates = debtSums.reduce((prev, curr) => {
const alreadyPushedIndex = prev.findIndex(i => i.Name === curr.Name);
if (alreadyPushedIndex === -1) {
prev.push(curr);
}
return prev;
}, []);
return removeDuplicates;
}
Maybe it could be a bit more optimised but it does what you want :)
the below code may help you.
const arr = [
{
"Name": "Mike",
"Age": "24",
"debt": "1000"
},
{
"Name": "Mike",
"Age": "24",
"debt": "2000"
},
{
"Name": "Nathan",
"Age": "26",
"debt": "500"
},
];
let unique = []
for (let char of arr) {
let check = unique.find(e=> {
if(char.Name == e.Name){
e.debt = parseInt(e.debt) + parseInt(char.debt)
return true
}
return false;
})
if(!check) {
unique.push(char)
}
}
Hey i tried to transform a json file (as a js object but I can not do it). Here is an example of my problem:
Input object
{
"peoples": [
{
"name": "Alain",
"nationality": "Italian"
},
{
"name": "John",
"nationality": "French"
},
{
"name": "FOO",
"nationality": "French"
}
]
}
Output object
{
"nationality": {
"french": {
"peoples": [{ "name": "John" }, { "name": "FOO" }]
},
"italian": {
"peoples": [{ "name": "Alain" }]
}
}
}
How can i do this ? maybe Lodash but i have not find any way to do this. Can anyone help me ?
You can use a simple reduce:
const obj = {
"peoples": [{
"name": "Alain",
"nationality": "Italian"
},
{
"name": "John",
"nationality": "French"
},
{
"name": "FOO",
"nationality": "French"
}
]
}
const output = obj.peoples.reduce((a, {nationality: n, ...rest}) => {
const x = a.nationality[n]
if (x) x.push(rest)
else a.nationality[n] = [rest]
return a
}, { nationality: {} })
console.log(output)
Note, I've used a spread operator to get the rest of the properties, so if you were to add more properties to each person, then those would be included in the new object.
I'm trying to make a comparison of the object properties by key.
There are some sample data:
const data = [{
"name": "John",
"value": "30"
}, {
"name": "Cindy",
"value": "50"
}, {
"name": "Mathew",
"value": "80"
}, {
"name": "Mike",
"value": "35"
}];
so I would like to compare property values(value) of John and Mike names(key). If value of Mike is different than John than mutate value of Mike with value of John.
There is some algorithm
data.map(obj => {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
let johnValue;
let mikeValue;
if(obj[key] == 'John') {
johnValue = Number(obj.value)
}
else if(obj[key] == 'Mike') {
mikeValue = Number(obj.value)
}
if(johnValue != mikeValue) {
newData = {
...data,
"Mike": johnValue
}
}
}
}
})
after whose execution I expected data like
const data = [{
"name": "John",
"value": "30"
}, {
"name": "Cindy",
"value": "50"
}, {
"name": "Mathew",
"value": "80"
}, {
"name": "Mike",
"value": "30"
}];
Is there a way to write it better using some of the ES6 features?
Fiddle
Yes, you can do it a bit shorter
const MikeRecordInd = data.findIndex(v => v.name === 'Mike')
const JohnRecord = data.find(v => v.name === 'John')
if (data[MikeRecordInd].value !== JohnRecord.value) {
newData = [...data]
newData[MikeRecordInd] = { name: 'Mike', value: JohnRecord.value }
}
I'm making an app with Express, Postgres and Sequelize.
I have a json that looks like this:
{
"names": [
{
"id": 1,
"name": "John",
"surname": "Smith"
},
{
"id": 2,
"name": "Peter",
"surname": "Black"
},
{
"id": 3,
"name": "Marie",
"surname": "White"
}
]
}
If I write one of their names in the query, case insensitive, I would like to return the whole element.
For example, if I query mari I want to return:
{
"id": 3,
"name": "Marie",
"surname": "White"
}
Like this I managed to get only the value, but not the whole entry (I need the id)
const names = persons.map(a => a.name);
const surnames = persons.map(a => a.surname);
const namesSurnames = names.concat(surnames)
const el = namesSurnames.find(a => a.includes(req.query.keyword));
console.log('el:', el);
You can use the .filter method and use .toLowerCase() and includes to search for let's say the keyword mari in the name or surname key.
const sample = {
"names": [
{
"id": 1,
"name": "John",
"surname": "Smith"
},
{
"id": 2,
"name": "Peter",
"surname": "Black"
},
{
"id": 3,
"name": "Marie",
"surname": "White"
}
]
};
const query = 'mari';
const name = sample.names.filter((user) => {
return user.name.toLowerCase().includes(query.toLowerCase()) || user.surname.toLowerCase().includes(query.toLowerCase());
});
if (name.length > 0) {
console.log(name[0]);
} else {
console.error('NO NAME FOUND!');
}
I want to sort some Object look likes this
data = {
"imH3i4igFNxM3GL": {
"name": "Nacky",
"age": 12
},
"vuzPuZUmyT8Z5nE": {
"name": "Emmy",
"age": 20
},
"OkIPDY1nGjxlq3W": {
"name": "Nat",
"age": 20
}
}
I want to sort it by "name".
I tried to use Lodash for this problem.
_.sortBy(data, [function(o) { return o.name; }]);
but, it return me an array of objects without the keys
[
{
"name": "Emmy",
"age": 20
},
{
"name": "Nacky",
"age": 12
},
{
"name": "Nat",
"age": 20
}
]
I want it return me sorted object with key like the same
{
"vuzPuZUmyT8Z5nE": {
"name": "Emmy",
"age": 20
},
"imH3i4igFNxM3GL": {
"name": "Nacky",
"age": 12
},
"OkIPDY1nGjxlq3W": {
"name": "Nat",
"age": 20
}
}
what should I do? thanks
Objects in JS can't be sorted, and the order of the properties is not reliable, ie it depends on browsers' implementations. That's why _.sortBy() is converting your object into a sorted array.
I can think of 2 options to work with that.
Add the key to the objects in the array
If you just need an ordered array with the keys in the objects, so you can render a list.
var data = {
"imH3i4igFNxM3GL": {
"name": "Nacky",
"age": 12
},
"vuzPuZUmyT8Z5nE": {
"name": "Emmy",
"age": 20
},
"OkIPDY1nGjxlq3W": {
"name": "Nat",
"age": 20
}
};
var result = _(data)
.map(function(v, k) { // insert the key into the object
return _.merge({}, v, { key: k });
})
.sortBy('name') // sort by name
.value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Create an order array
Create an array of ordered keys, and use them when you wish to render the objects in order.
var data = {
"imH3i4igFNxM3GL": {
"name": "Nacky",
"age": 12
},
"vuzPuZUmyT8Z5nE": {
"name": "Emmy",
"age": 20
},
"OkIPDY1nGjxlq3W": {
"name": "Nat",
"age": 20
}
};
var orderArray = _(data)
.keys() // create an array of keys
.sortBy(function(key) { // sort the array using the original names
return data[key].name;
}) // sort by name
.value();
console.log('The order array', orderArray);
console.log(orderArray.map(function(k) {
return data[k];
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
I use something like this.
let data = {
'g34ghgj3kj': {
YOUR_KEY: 'g34ghgj3kj',
'key1': false,
'key2': false,
},
'hh334h664': {
YOUR_KEY: 'hh334h664',
'key1': true,
'key2': false,
},
//{...}
};
_.orderBy(data, ['key1', 'key2'], ['desc', 'desc']).reduce((result, value) => {
result[value.YOUR_KEY] = value;
return result;
}, {});