I have an array of object from which I am trying to get values using map operator but I am getting the whole json objects all I want is just array of values.
Below is my code:
const obj = [
{
a: {
b: 'Paul',
}
},
{
c: 'Byeeee',
}
];
obj.map((val) => console.log(val));
what I am getting is
{ a: { b: 'Paul' } }
{ c: 'Byeeee' }
What I want is:
['Paul','Byeeee']
Someone let me know how can I get the desired output.
You can do this recursively. You can first start off by grabbing the values of your object, and then loop through those using .flatMap(). If you encounter a value that is an object, you can recursively grab the values of that object by recalling your function. Otherwise, you can return the value. The advantage of using .flatMap() here is that when the recursive call returns an array, we don't end up with inner arrays, but rather the array gets flattened into one resulting array:
const obj = [{ a: { b: 'Paul', } }, { c: 'Byeeee', } ];
const getValues = (obj) => {
return Object.values(obj).flatMap(val => Object(val) === val ? getValues(val) : val);
}
console.log(getValues(obj));
you can use the following solution.
const data = [{ a: { b: 'Paul' } }, { c: 'Byeeee' }];
const flatObjectValues = (obj, result) => {
// recursive function to get object values
const objValues = Object.values(obj);
if (objValues?.length > 0) {
objValues.map((v) => {
if (typeof v === 'object' && !Array.isArray(v)) {
flatObjectValues(v, result);
} else {
result.push(v);
}
return v;
});
}
};
const updatedData = [];
data.map((x) => flatObjectValues(x, updatedData));
console.log('updatedData: ', updatedData);
You can use recursion with array.reduce, like fellowing.
function getAllValues(objuct) {
return objuct.reduce((acc, curr) => {
if (typeof curr === 'object') {
return [...acc, ...getAllValues(Object.values(curr))];
}
return [...acc, curr];
}, []);
}
A recursive solution could be:
const arr = [{a: {b: "Paul",},},{c: "Byeeee",},];
const flatArrOfObjects = (arr) => {
const values = [];
for (const i in arr) flatObj(arr[i], values);
return values;
};
const flatObj = (obj, result) => {
for (const [key, value] of Object.entries(obj)) {
if (typeof value === "object") flatObj(value, result);
else result.push(value);
}
};
console.log(flatArrOfObjects(arr));
Related
This question already has answers here:
Filter object properties by key in ES6
(30 answers)
Closed 1 year ago.
I'm trying to create an object from object and list of properties.
const pick = (obj, ...fields) => {
return [...fields] = obj
};
How can I realise this?
Reduce the list of fields, and take the values from the original object:
const pick = (obj, ...fields) => fields.reduce((acc, field) => ({ ...acc, [field]: obj[field] }), {});
const obj = { a: 1, b: 2, c: 3 };
const result = pick(obj, 'a', 'c');
console.log(result);
You can use the in operator to ignore properties that don't exist on the original object:
const pick = (obj, ...fields) => fields.reduce((acc, field) => {
const value = obj[field];
if(field in obj) acc[field] = value;
return acc;
}, {});
const obj = { a: 1, b: 2, c: 3 };
const result = pick(obj, 'a', 'c', 'd');
console.log(result);
Try something like this:
const pick = (obj, ...fields) => Object.fromEntries(Object.entries(obj).filter(([k]) => fields.includes(k)))
Iterate through fields array and check if property is available in obj then put into final object which needs to be returned.
const pick = (obj, ...fields) => {
const finalObj = { };
for (field of fields) {
if (obj[field]) {
finalObj[field] = obj[field];
}
}
return finalObj;
};
const obj = { name: "test name", age: 25, title: "Mr.", city: "test city" };
console.log(pick(obj, "name", "age", "city", "other"));
I want to get the length of values from an object. If the value has no length i should get 0 length, if value exists i should get value.
const object1 = {
a: '',
b: '5'
};
function app() {
for (const [key, value] of Object.entries(object1)) {
console.log(key, value)
return {
[key]: !object1[key].length ? '0 length' : value
}
}
}
console.log(app())
Question:
Why i get just first value from object?
{
"a": "0 length"
}
expect:
{
"a": "0 length",
"b": 1
}
Why now i get in console.log(key, value) just the first value-key, but if i delete the return statement i get both value-key?
const object1 = {
a: '',
b: '5'
};
function app() {
for (const [key, value] of Object.entries(object1)) {
console.log(key, value)
// return {
// [key] : !object1[key].length ? '0 length' : value
// }
}
}
console.log(app())
Because you are returning from very first value inside for you are getting only one value in result.
Instead of that take one variable for ex let result = {}; Assign length values to it inside for as result[key] = value.toString().length || '0 length'; and then return result;.
Try it below.
const object1 = {
a: '',
b: '5'
};
function app() {
let result = {};
for (const [key, value] of Object.entries(object1)) {
// console.log(key, value)
result[key] = value.toString().length || '0 length';
}
return result;
}
console.log(app());
If your expected output is array then use like below. For array result you can also use map with like shown in app2.
const object1 = {
a: '',
b: '5'
};
function app() {
let result = [];
for (const [key, value] of Object.entries(object1)) {
result.push({[key]: value.toString().length || '0 length'});
}
return result;
}
function app2() {
return Object.entries(object1).map(([key, value]) => ({[key]: value.toString().length || '0 length'}));
}
console.log(app());
console.log(app2());
return exits the loop after first iteration
Perhaps you should do something like this
const object1 = {
a: '',
b: '5'
};
const newObj = {};
function app() {
for (const [key, value] of Object.entries(object1)) {
console.log(key, value)
newObj[key] = !object1[key].length ? '0 length' : value
}
return newObj;
}
console.log(app())
const object1 = {
a: '',
b: '5'
};
function app() {
const result = [];
for(let key in object1) {
if(object1[key] && object1[key].length) {
result.push({[key] :`${object1[key].length} length`});
} else {
result.push({[key] :`0 length`});
}
}
return result;
}
console.log(app())
As a part of a challenge I need to implement the .findKey() method myself. Below is the solution proposition, however, I get an error "predicate is not a function".
const _ = {
findKey(object, predicate) {
for (let key in object) {
let value = object[key];
let predicateReturnValue = predicate(value);
if (predicateReturnValue) {
return key;
};
};
undefined
return undefined;
}
};
Can anyone help?
function findKey(object, predicate) {
for (let key in object) {
let value = object[key];
let predicateReturnValue = predicate(value);
if (predicateReturnValue) { // just take the value
return key; // return key
}
}
}
const isEqual = a => b => a === b
const object = { a: 'Apple', b: 'Beer', c: 'Cake' }
alert(findKey(object, isEqual('Apple')));
alert(findKey(object, isEqual('Cakes')));
This question already has answers here:
Remove from JS object where key value is an empty array
(2 answers)
Closed 2 years ago.
I have got object of array. I am trying to check empty.
const data = {
test:[],
test2:[],
test1:["can"]
}
Here is my trying code:
const dataObj = Object.values(data)
console.log(dataObj)
my output would be :
const data = {
test1:["can"]
}
You can use Object.entries and Array#reduce methods.
const data = {
test: [],
test2: [],
test1: ["can"]
}
const res = Object.entries(data).reduce((obj, [k, v]) => {
if (v && v.length) obj[k] = v;
return obj;
}, {})
console.log(res)
Or with for...of loop.
const data = {
test: [],
test2: [],
test1: ["can"]
}
const res = {};
for (let [k, v] of Object.entries(data)) {
if (v && v.length) res[k] = v;
}
console.log(res)
const data = {
test: [],
test2: [],
test1: ["can"],
test3: ["hi"]
}
for (let [key, value] of Object.entries(data)) {
if (value.length) {
console.log(`${key}: not emty`)
} else {
console.log(`${key}: emty`)
}
}
I'm using the following piece of code (which is working fine)
const result = {}
Object.keys(timers).forEach(key => {
result[key] = hydrate(timers[key])
})
return result
}
I'm wondering if this is possible in one method? So without having to fill the result object?
Convert to entries with Object.entries(), iterate the entries with Array.map() and hydrate the values, and convert back to an object with Object.fromEntries():
const fn = timers => Object.fromEntries(
Object.entries(timers).map(([k, v]) => [k, hydrate(v)])
)
Just use reduce
var timers = {
a: 2,
b: 3,
c: 4
}
const hydrate = x => 2*x
var result = Object.entries(timers).reduce((o, [key, value]) => {
o[key] = hydrate(value)
return o
}, {})
console.log(result)
without fat arrow
var timers = {
a: 2,
b: 3,
c: 4
}
function hydrate (x) { return 2 * x }
var result = Object.entries(timers).reduce(function(o, entry) {
o[entry[0]] = hydrate(entry[1])
return o
}, {})
console.log(result)