How to transform attribute values into keys? [duplicate] - javascript

This question already has answers here:
Convert object array to hash map, indexed by an attribute value of the Object
(21 answers)
Closed 4 years ago.
I have a JSON in the format.
var input = [
{status:"good", state: "NY"},
{status:"bad", state: "FL"},
{status:"decent", state: "CA"}
]
I want to transform it in an object of the format:
myObj = {NY:"good",FL:"bad",CA:"decent"}
The reason I want this is so that I can easily grab the myObj.NY value.

Short and simple
var input = [
{status:"good", state: "NY"},
{status:"bad", state: "FL"},
{status:"decent", state: "CA"}
]
var obj = {};
input.forEach(function(k) {
obj[k.state] = k.status;
});
console.log(obj);

You can try using "Object.assign" and "Array.map" as well like below to achieve your desired result
var input = [
{status:"good", state: "NY"},
{status:"bad", state: "FL"},
{status:"decent", state: "CA"}
]
let res = Object.assign(...input.map(({ state, status}) => ({ [state]: status })))
console.log(res)

var myobj = {};
Input.forEach(function (i) { myobj[i.status] = i.state;}

You can do a simple forEach() loop on that array with array destructuring to make your code short and simple.
var input = [{
status: "good",
state: "NY"
},
{
status: "bad",
state: "FL"
},
{
status: "decent",
state: "CA"
}
];
var res = {};
input.forEach(({state, status})=> res[state] = status);
console.log(res);

Using Array.prototype.reduce()
var myObj = input.reduce( (r,x) => { r[x.status] = x.state ; return r }, {})

This can be accomplished as well using map, by assigning the object key through the [key] syntax:
var input = [
{status:"good", state: "NY"},
{status:"bad", state: "FL"},
{status:"decent", state: "CA"}
]
var myObj = Object.assign({}, ...input.map(item => ({
[item.state]: item.status
})));
console.log(myObj);
see https://jsfiddle.net/gL6bcqm1/1/

Related

Best way to convert array to object [duplicate]

This question already has answers here:
How to convert an array into an object in javascript with mapped key-value pairs?
(4 answers)
Closed 10 months ago.
What is the best way to convert this
const items = [
{ name: "Leon", url: "../poeple" },
{ name: "Bmw", url: "../car" }
];
into this using javascript :
const result = {
Leon: "../poeple",
Bmw: "../car"
};
You could just reduce the array:
const items = [{
name: "Leon",
url: "../people"
},
{
name: "Bmw",
url: "../car"
}
];
const o = items.reduce((o, el) => {
o[el.name] = el.url;
return o;
}, {});
console.log(o)
The Array.prototype.reduce method is very flexible, and might be used to reduce an array to another entity:
The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
You could map the objects as entries and get an object from it.
const
items = [{ name: "Leon", url: "../poeple" }, { name: "Bmw", url: "../car" }],
result = Object.fromEntries(items.map(({ name, url }) => [name, url]));
console.log(result);
There are lots of different approaches as your can see. But if you're new to JavaScript maybe a simple loop over the array to create new keys and values in a new object would be easier to understand.
const items=[{name:"Leon",url:"../poeple"},{name:"Bmw",url:"../car"}];
const out = {};
for (const obj of items) {
out[obj.name] = obj.url;
}
console.log(out);
Another way (tested on your example):
function convertit (src) {
var dest = {}, i;
for (i = 0; i < src.length; i++) {
var record = src[i];
dest[record.name] = record.url;
}
return dest;
}
Try Like This
const items = [
{ name: "Leon", url: "../poeple" },
{ name: "Bmw", url: "../car" }
];
const newObj = Object.fromEntries(items.map(ele => [ele.name,ele.url]));
console.log(newObj);
Or You can create function like this
const items = [
{ name: "Leon", url: "../poeple" },
{ name: "Bmw", url: "../car" }
];
const convertArrayToObject = (array, key) => {
const initialValue = {};
return array.reduce((obj, item) => {
return {
...obj,
[item[key]]: item.url,
};
}, initialValue);
};
console.log(convertArrayToObject(items, "name"));

How to change the value of matching property using json-query?

I using json-query because it lets me find by path inside the JSON object.
After I find it I want to replace the value with a new value and I expected it to affect the string, but it doesn't.
Is there a way to do it using with json-query? or rebuild this JSON again from the object but I can't find a way in the docs.
const jsonQuery = require("json-query");
var data = {
people: [
{ name: "Matt", country: "NZ" },
{ name: "Pete", country: "AU" },
{ name: "Mikey", country: "NZ" }
]
};
const b = jsonQuery("people[country=NZ].name", {
data: data
});
console.log({ b });
b.value = "bla";
console.log({ b }); // value === 'bla'
console.log({ data }); // value === 'Matt'
codesandbox.io
You can modify the entry in the reference subproperty returned by the query:
const b = jsonQuery("people[country=NZ].name", {
data: data
});
b.references[0].name = 'bla';
See proof-of-concept example: https://codesandbox.io/s/wonderful-kirch-g7zy2

Joining two arrays of JSON objects like an SQL join using functional programming

Consider, I have the following two arrays of objects:
const existingAndArchivedBookings =
[
{"booking_id":-2},
{"booking_id":-1},
{"booking_id":999}
]
const newAndExistingBookings =
[
{bookingId:-2, name: "name1"},
{bookingId:-3, name: "name1"},
{bookingId:-1, name: "namex"}
]
What I want to do is determine which of the bookings in the second array are new and which are existing. Any bookingId that is in both arrays is existing. Any bookingID that is in the second array but not the first is new. So, the result of the solution should be an array as follows:
[ { bookingId: -2, existing: true, name: 'name1' },
{ bookingId: -3, existing: false, name: 'name1' },
{ bookingId: -1, existing: true, name: 'namex' } ]
I have a solution (which I'll post as an answer), but I think there's probably a more efficient way of doing it. Good luck.
If you want a non-R answer: you can use a simple map to iterate over the data, compare the booking ids in both arrays (with some), and return a new array of objects.
const existingAndArchivedBookings = [{booking_id:-2},{booking_id:-1},{booking_id:999}];
const newAndExistingBookings = [{bookingId:-2, name: "name1"},{bookingId:-3, name: "name1"},{bookingId:-1, name: "namex"}];
function testBookings(arr1, arr2) {
return arr2.map(({ bookingId, name }) => {
const existing = arr1.some(obj => obj.booking_id === bookingId);
return { bookingId, existing, name };
});
}
const out = testBookings(existingAndArchivedBookings, newAndExistingBookings);
console.log(out);
You can greatly simplify it using Array.prototype.reduce to form the result of the comparisons between the 2 arrays and Array.prototype.findIndex to test whether the object in the second array is present in the first array:
const existingAndArchivedBookings =
[
{"booking_id":-2},
{"booking_id":-1},
{"booking_id":999}
]
const newAndExistingBookings =
[
{bookingId:-2, name: "name1"},
{bookingId:-3, name: "name1"},
{bookingId:-1, name: "namex"}
]
const res = newAndExistingBookings.reduce((acc, ele) => {
const idx = existingAndArchivedBookings.findIndex(b => b.booking_id === ele.bookingId);
let existing = false;
if(idx >=0 ){
existing = true;
}
return acc.concat({bookingId : `${ele.bookingId}`, existing: `${existing}`, name: `${ele.name}`});
}, []);
console.log(res);
Here's what I came up with, which seems a bit long winded
const R = require('ramda')
const existingAndArchivedBookings = [{"booking_id":-2},{"booking_id":-1},{"booking_id":999}]
const newAndExistingBookings = [{bookingId:-2, name: "name1"}, {bookingId:-3, name: "name1"}, {bookingId:-1, name: "namex"}]
const existingAndArchivedKeys = existingAndArchivedBookings.map(value => value.booking_id)
const newAndExistingKeys = newAndExistingBookings.map(value => value.bookingId)
const existingKeys = existingAndArchivedKeys.filter(key => newAndExistingKeys.includes(key))
const newKeys = newAndExistingKeys.filter(key => !existingAndArchivedKeys.includes(key))
const existingBookingIds = existingKeys.map(key => {
return {bookingId: key, existing: true}
})
const newBookingIds = newKeys.map(key => {
return {bookingId: key, existing: false}
})
const allArray = R.concat(newAndExistingBookings, R.concat(existingBookingIds, newBookingIds))
console.log(R.values(R.reduceBy(R.mergeLeft, {}, R.prop('bookingId'), allArray)))

Change array in to object in react js [duplicate]

This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Convert Javascript array of objects into one object
(4 answers)
Closed 3 years ago.
This is my array format
let array = [
0: {
key:"name",
value: "John"
},
1: {
key:"age",
value:25
},
2: {
key:"job",
value:"software engineer"
},...
];
Change this array to object in given below format
{
name: "John",
age: 27,
job: "software engineer"
}
You can achieve it using forEach on the array.
Give this a try:
const array = [{
key: "name",
value: "John"
}, {
key: "age",
value: 25
}, {
key: "job",
value: "software engineer"
}];
const expected = {};
array.forEach(item => expected[item.key] = item.value);
console.log(expected);
You can use Array.prototype.reduce() to do this:
let array = [
{
key:"name",
value: "John"
},
{
key:"age",
value:25
},
{
key:"job",
value:"software engineer"
}
];
let result = array.reduce((a,b) => {
a[b.key] = b.value;
return a;
}, {});
console.log(result);
All you need to do is to loop over the array using forEach, for loop, while loop etcand push the values in a new object.
Also make sure that your array syntax is correct because the way you have mentioned it in the question is incorrect.
const data = [{ key:"name", value: "John" },{ key:"age", value:25 },{ key:"job", value:"software engineer" } ];
const res = {};
data.forEach(item => { res[item.key] = item.value});
console.log(res);

Filter array items using forEach

I have one question about filter array in forEach. So I would like filter (bigger than in example) array using outside variable filterKey. I think that my function is correct by after filtered newArr is undefined. Could you explain what is incorrect?
var filterKey = 123456,
var array = [{
ratings:{ users:[id: 123456]}, user: xyz
},
{
ratings:{users:[id:9787389023]}, user:zyx
}],
And my filter function
var newArr = array.forEach((ele) =>
ele.ratings.users.filter((newEl) =>
newEl.id == filterKey))
Use array.filter method
let array = [
{
id: 123456, user: 'xyz'
},
{
id:9787389023, user: 'zyx'
},
{
id: 123456, user: 'che'
}
]
let newArray = array.filter((element) => element.id === 123456)
console.log(newArray)
Use .filter and you'll be able to filter your result set without using foreach since it'll loop across the array.
var find = 123456;
var arr = [
{
id: 123456,
user: 'john'
},
{
id: 9787389023,
user: 'leah'
}
];
var results = arr.filter(function(node) {
return node.id === find;
});
console.log(results);

Categories

Resources