merging nested lists and map in ruby - arrays

I have following list of maps, how can I get values inside map out and merge them as a new list
Example:
x = [ { "key1" => [{"K1" =>"123", "K2" =>"123"}] },
{ "key1" => [{"K3" =>"23", "K4" =>"32"}] },
{ "key1" => [{"K5" =>"34", "K6" =>"23"}] }]
What I want is:
[{"K1" =>"123", "K2" =>"123"},
{"K3" =>"23", "K4" =>"32"},
{"K5" =>"34", "K6" =>"23"}]

You can try the below -
x = [ { "key1" => [{"K1" =>"123", "K2" =>"123"}] },
{ "key1" => [{"K3" =>"23", "K4" =>"32"}] },
{ "key1" => [{"K5" =>"34", "K6" =>"23"}] }]
y = x.map{|h| h.map{|i,j| j} }.flatten
print(y)
This prints the below
[{"K1"=>"123", "K2"=>"123"}, {"K3"=>"23", "K4"=>"32"}, {"K5"=>"34", "K6"=>"23"}]

x.flat_map(&:entries).group_by(&:first).map{|k,v| Hash[k, v.map(&:last)]}
as:
> x = [ { "key1" => [{"K1" =>"123", "K2" =>"123"}] },
{ "key1" => [{"K3" =>"23", "K4" =>"32"}] },
{ "key1" => [{"K5" =>"34", "K6" =>"23"}] }]
> x.flat_map(&:entries).group_by(&:first).map{|k,v| Hash[k, v.map(&:last)]}
=> [{"key1"=>[[{"K1"=>"123", "K2"=>"123"}], [{"K3"=>"23", "K4"=>"32"}], [{"K5"=>"34", "K6"=>"23"}]]}]
I hope that helpful

You can simply do as below,
x.map { |z| z.values[0][0] }
# => [{"K1"=>"123", "K2"=>"123"}, {"K3"=>"23", "K4"=>"32"}, {"K5"=>"34", "K6"=>"23"}]

Related

How to Save an Array data in JSON using LARAVEL Controller

I want to save this data generated by a create.blade.php view,
after I press submit button, the console log output is like the code below
{
"kode_trx": "PO-2019030004",
"no_po": "0005/DIN/III/2019",
"pic_po": "Carlo Donadini",
"pic_telp": "+39438778020",
"top": "RRRRR",
"supplier_id": "1",
"delivery_date": "28-03-2019",
"created_by_id": "1",
"total_barang": "7",
"grand_total": "122500000",
"tb_detail_po": [
[
"BRG-2019030004",
"Electric Deep Fryer",
"SC-81",
"290",
"440",
"310",
"4",
"17500000",
"70000000",
" ",
"4",
"PO-2019030004",
"0005/DIN/III/2019",
"1",
"5"
],
[
"BRG-2019030004",
"Electric Deep Fryer",
"SC-81",
"290",
"440",
"310",
"3",
"17500000",
"52500000",
" ",
"4",
"PO-2019030004",
"0005/DIN/III/2019",
"1",
"5"
]
]
}
so I want to save it into 2 differen table, table purchases and purchase_details
how I suppose to write my code in POController in method store? ???
You can store the data on table purchase like below
class POController extends Controller
{
public function store(Request $request)
{
$purchase = Purchase::create([
"id_penerimaan" => $request->no_nota,
"id_customer" => $request->customer,
"id_karyawan" => $request->karyawan,
"tgl_penerimaan" => \Carbon\Carbon::now()->format('Y-m-d H:i:s'),
]);
return $purchase;
}
}
And for the table purchase_details if you use Observer it would be great
Example of Observer :
class UserObserver
{
public function created(Purchase $purchase)
{
if (request()->tb_detail_po) {
foreach(request()->tb_detail_po as $detail) {
PurchaseDetail::create([
'id_purchase' => $purchase->id,
'id_penerimaan' => request()->no_nota,
'id_karyawan' => $detail[9],
'id_kategori' => $detail[8],
'sn_barang' => $detail[1],
'nama_barang' => $detail[0],
'kelengkapan' => $detail[2],
'keluhan' => $detail[3],
'id_garansi' => $detail[10],
'id_status' => '1',
'kondisi' => '1'
]);
}
}
}
}
$result = $request->all();
$created = Your Model::create([Your Data For Table 1]);
if($created) {
foreach($request->tb_detail_po as $details) {
Your Model2::create([Your Detail Data For Table 2]);
}
}
Try to use **JSON_DECODE($data)** OR **JSON_ENCODE($data)**

Searching for data in arrays [Node.JS]

I have a question:
(sorry for the bad formatting)
I have an array:
[
{
"data": [
[
"kek",
"lol"
],
[
"notkek",
"notlol"
]
]
}
]
If someone writes "kek" it should search it in the "data" array and return the "kek" position inside its array
(["kek","lol"])
and its array position
{
"data": [
[
"kek",
"lol"
]}
(in this case "data[0]")
If anybody knows the answer, please help me
The method Array.findIndex and Array.includes may help you
const obj = {
data: [
[
'kek',
'lol'
],
[
'notkek',
'notlol'
],
],
};
const keyToSearch = 'kek';
// We look for the key
const index = obj.data.findIndex(x => x.includes(keyToSearch));
if (index === -1) {
console.log(`We didn't found ${keyToSearch}`);
} else {
console.log(`We found ${keyToSearch} at index ${index}`);
}
Double index recuperation
const obj = {
data: [
[
'kek',
'lol'
],
[
'notkek',
'notlol'
],
[
'notkek',
'notlol',
'otherstuff',
'kek',
'test',
],
],
};
const keyToSearch = 'kek';
const ret = obj.data.reduce((tmp, x, xi) => {
// We look for the key
const index = x.findIndex(y => y === keyToSearch);
if (index === -1) return tmp;
return [
...tmp,
{
absoluteIndex: xi,
relativeIndex: index,
},
];
}, []);
if (!ret.length) {
console.log(`We didn't found ${keyToSearch}`);
} else {
ret.forEach(({
absoluteIndex,
relativeIndex,
}) => console.log(
`We found ${keyToSearch} at`,
`data index ${absoluteIndex}, in ${relativeIndex} position`,
));
}
userInput = 'kek'
let item = data.map((item, indx) => {
item.includes(userInput) ? return({"indx":indx,"nestedIndex":item.indexOf(userInput)}) : null
})
map over the data array and if the nested array had the item your searching for than return the index of the array and the index of the item with in that array

Laravel Where Collection

I am having troubles with laravel collections. This is my script:
foreach($getResult->all()['results'] as $key => $val) {
$colVal = collect($val);
$dataDiff = [];
$getWithoutLine = $colVal->except(['line_items']);
$getDiff = $colVal->only(['line_items']);
foreach($colVal->all()['line_items'] as $val1) {
if ((int)$val1['quantity'] - (int)$val1['deliveries']['quantity'] > 0) {
$getWithoutLine['status'] = 'partially_received';
$dataDiff[] = $val1;
}
}
$getWithoutLine['line_items'] = $dataDiff;
//dd($getWithoutLine);
$filtered = $getWithoutLine->whereStrict('status', 'submitted');
//dd($filtered->all());
$getFullCol[] = $filtered;
}
When dd($getWithoutLine) is executed, then collection appears like this:
Collection {#464
#items: array:24 [
"id" => "13c023aa-b471-4276-a0fc-a22d3677be91"
"status" => "submitted"
"date" => "2018-09-19"
"time" => "11:54:22"
"number" => "PO000003"
"description" => "Pesanan Pembelian, Vendor 1"
"supplier" => array:4 [
"id" => null
"code" => null
"name" => null
"classification" => null
]
"term_of_payment" => array:6 [
"due_date" => null
"due_days" => 0
"late_charge_rate" => 0.0
"discount_date" => null
"discount_days" => 0
"early_discount_rate" => 0.0
]
...
...
]
}
But when dd($filtered->all()) is executed then the result is empty. Why is that?
I can't understand what I am doing wrong.
=======
EDITED
When I change dd($filtered->all()) to dd($filtered) the result is actually same :
Collection {#463
#items: []
}
======
EDITED
When I Change $filtered = $getWithoutLine->whereStrict('status', 'submitted'); to $getWithoutLine->only('status'); the collection is work...
Collection {#468
#items: array:1 [
"status" => "submitted"
]
}

Ruby pick up a value in hash of array to reformat into a hash

Is there a way I can pick a value in hash of array, and reformat it to be only hash?
Is there any method I can do with it?
Example
[
{
"qset_id" => 1,
"name" => "New1"
},
{
"qset_id" => 2,
"name" => "New2"
}
]
Result
{
1 => {
"name" => "New1"
},
2 => {
"name" => "New2"
}
}
You can basically do arbitary manipulation using reduce function on array or hashes, for example this will get your result
array.reduce({}) do |result, item|
result[item["qset_id"]] = { "name" => item["name"] }
result
end
You can do the same thing with each.with_object do:
array.each.with_object({}) do |item, result|
result[item["qset_id"]] = { "name" => item["name"] }
end
it's basically the same thing but you don't have to make each iteration return the result (called a 'memo object').
You could iterate over the first hash and map it into a second hash:
h1.map{|h| {h['qset_id'] => {'name' => h['name']}} }
# => [{1=>{"name"=>"New1"}}, {2=>{"name"=>"New2"}}]
... but that would return an array. You could pull the elements into a second hash like this:
h2 = {}
h1.each do |h|
h2[h['qset_id']] = {'name' => h['name']}
end
>> h2
=> {1=>{"name"=>"New1"}, 2=>{"name"=>"New2"}}

Parsing a HoAoHoAoHoAoH in Perl

I am new to Perl and have a little idea about hashes. I have a hash of array of hash of array of hash of array of hash (HoAoHoAoHoAoH) as follows.
%my_hash = (
key00 => 'value00',
key01 => [
{ key10 => 'value10',
key11 => 'value11',
key12 => [
{ key20 => 'value20',
key21 => 'value21',
key22 => [
{ key30 => 'value30',
key31 => [
{ color => 'blue', quantity => 10, boxes => [0,1,3] },
{ color => 'red', quantity => 2, boxes => [2,3] },
{ color => 'green', quantity => 5, boxes => [0] },
],
},
],
},
]
}
]
);
What is the easiest way to access the "color", "quantity" and "boxes"? I also need to do arithmetic operations with the "quantity"s, such as 10+2+5 (quantity0+quantity1+quantity2).
This looks a lot like an XY problem. What are you trying to solve here?
You can access an element of your data structure like this:
print $my_hash{key01}[0]{key12}[0]{key22}[0]{key31}[0]{color},"\n";
You can also iterate the bottom elements with:
foreach my $something ( #{ $my_hash{key01}[0]{key12}[0]{key22}[0]{key31} } ) {
print $something->{'color'};
print $something->{'quantity'}
}
But this doesn't look like a real problem - what are you actually trying to accomplish? I might guess you're trying to parse XML or similar, in which case there's almost certainly a better approach.

Resources